AccountContext refactoring

This commit is contained in:
Peter Iakovlev
2019-01-22 23:23:48 +04:00
parent 52e723906e
commit 56c367642b
15 changed files with 340 additions and 367 deletions

View File

@@ -164,7 +164,7 @@ class NotificationViewController: UIViewController, UNNotificationContentExtensi
strongSelf.imageNode.setSignal(chatMessagePhoto(postbox: accountAndImage.0.postbox, photoReference: imageReference))
accountAndImage.0.network.shouldExplicitelyKeepWorkerConnections.set(.single(true))
strongSelf.fetchedDisposable.set(chatMessagePhotoInteractiveFetched(account: accountAndImage.0, photoReference: imageReference, storeToDownloadsPeerType: nil).start())
strongSelf.fetchedDisposable.set(standaloneChatMessagePhotoInteractiveFetched(account: accountAndImage.0, photoReference: imageReference).start())
}
}))
}

View File

@@ -180,23 +180,21 @@ class ShareRootController: UIViewController {
let shouldBeMaster = self.shouldBeMaster
let applicationInterface = account
|> mapToSignal { account, accountManager -> Signal<(Account, PostboxAccessChallengeData), ShareAuthorizationError> in
|> mapToSignal { account, accountManager -> Signal<(AccountContext, PostboxAccessChallengeData), ShareAuthorizationError> in
return combineLatest(currentPresentationDataAndSettings(postbox: account.postbox), account.postbox.combinedView(keys: [.accessChallengeData, preferencesKey]) |> take(1))
|> deliverOnMainQueue
|> introduceError(ShareAuthorizationError.self)
|> map { dataAndSettings, data -> (Account, PostboxAccessChallengeData) in
|> map { dataAndSettings, data -> (AccountContext, PostboxAccessChallengeData) in
accountCache = (account, accountManager)
updateLegacyLocalization(strings: dataAndSettings.presentationData.strings)
account.applicationContext = TelegramApplicationContext(applicationBindings: applicationBindings, accountManager: accountManager, account: account, initialPresentationDataAndSettings: dataAndSettings, postbox: account.postbox)
return (account, (data.views[.accessChallengeData] as! AccessChallengeDataView).data)
let context = AccountContext(account: account, applicationBindings: applicationBindings, accountManager: accountManager, initialPresentationDataAndSettings: dataAndSettings, postbox: account.postbox)
return (context, (data.views[.accessChallengeData] as! AccessChallengeDataView).data)
}
}
|> afterNext { account, _ in
setupAccount(account)
}
|> deliverOnMainQueue
|> afterNext { [weak self] account, accessChallengeData in
updateLegacyComponentsAccount(account)
|> afterNext { [weak self] context, accessChallengeData in
setupAccount(context.account)
setupLegacyComponents(context: context)
initializeLegacyComponents(application: nil, currentSizeClassGetter: { return .compact }, currentHorizontalClassGetter: { return .compact }, documentsPath: "", currentApplicationBounds: { return CGRect() }, canOpenUrl: { _ in return false}, openUrl: { _ in })
let displayShare: () -> Void = {
@@ -206,7 +204,7 @@ class ShareRootController: UIViewController {
return Signal { [weak self] subscriber in
switch content[0] {
case let .contact(data):
let controller = deviceContactInfoController(account: account, subject: .filter(peer: nil, contactId: nil, contactData: data, completion: { peer, contactData in
let controller = deviceContactInfoController(context: context, subject: .filter(peer: nil, contactId: nil, contactData: data, completion: { peer, contactData in
let phone = contactData.basicData.phoneNumbers[0].value
if let vCardData = contactData.serializedVCard() {
subscriber.putNext([.media(.media(.standalone(media: TelegramMediaContact(firstName: contactData.basicData.firstName, lastName: contactData.basicData.lastName, phoneNumber: phone, peerId: nil, vCardData: vCardData))))])
@@ -229,7 +227,7 @@ class ShareRootController: UIViewController {
}
let sentItems: ([PeerId], [PreparedShareItemContent]) -> Signal<ShareControllerExternalStatus, NoError> = { peerIds, contents in
let sentItems = sentShareItems(account: account, to: peerIds, items: contents)
let sentItems = sentShareItems(account: context.account, to: peerIds, items: contents)
|> `catch` { _ -> Signal<
Float, NoError> in
return .complete()
@@ -241,10 +239,10 @@ class ShareRootController: UIViewController {
|> then(.single(.done))
}
let shareController = ShareController(account: account, subject: .fromExternal({ peerIds, additionalText in
let shareController = ShareController(context: context, subject: .fromExternal({ peerIds, additionalText in
if let strongSelf = self, let inputItems = strongSelf.extensionContext?.inputItems, !inputItems.isEmpty, !peerIds.isEmpty {
let rawSignals = TGItemProviderSignals.itemSignals(forInputItems: inputItems)!
return preparedShareItems(account: account, to: peerIds[0], dataItems: rawSignals, additionalText: additionalText)
return preparedShareItems(account: context.account, to: peerIds[0], dataItems: rawSignals, additionalText: additionalText)
|> map(Optional.init)
|> `catch` { _ -> Signal<PreparedShareItems?, NoError> in
return .single(nil)
@@ -288,12 +286,12 @@ class ShareRootController: UIViewController {
strongSelf.mainWindow?.present(shareController, on: .root)
}
account.resetStateManagement()
account.network.shouldKeepConnection.set(shouldBeMaster.get()
context.account.resetStateManagement()
context.account.network.shouldKeepConnection.set(shouldBeMaster.get()
|> map({ $0 }))
}
let _ = passcodeEntryController(account: account, animateIn: true, completion: { value in
let _ = passcodeEntryController(context: context, animateIn: true, completion: { value in
if value {
displayShare()
} else {

View File

@@ -627,7 +627,7 @@ private enum QueuedWakeup: Int32 {
|> take(1)
|> deliverOnMainQueue).start(next: { context in
if let context = context {
self.registerForNotifications(account: context.account, authorize: true, completion: completion)
self.registerForNotifications(context: context.context, authorize: true, completion: completion)
}
})
}, requestSiriAuthorization: { completion in
@@ -678,7 +678,7 @@ private enum QueuedWakeup: Int32 {
|> take(1)
|> deliverOnMainQueue).start(next: { value in
if let value = value, case let .authorized(context) = value {
self.registerForNotifications(account: context.account, authorize: false)
self.registerForNotifications(context: context.context, authorize: false)
}
})
})
@@ -694,7 +694,7 @@ private enum QueuedWakeup: Int32 {
case let .unauthorized(unauthorized):
network = unauthorized.account.network
case let .authorized(authorized):
network = authorized.account.network
network = authorized.context.account.network
default:
break
}
@@ -703,27 +703,26 @@ private enum QueuedWakeup: Int32 {
Logger.shared.log("App \(self.episodeId)", "received context \(String(describing: context)) account \(String(describing: context?.accountId)) network \(String(describing: network))")
if let contextValue = self.contextValue {
(contextValue.account?.applicationContext as? TelegramApplicationContext)?.isCurrent = false
switch contextValue {
case let .unauthorized(unauthorized):
unauthorized.account.shouldBeServiceTaskMaster.set(.single(.never))
case let .authorized(authorized):
authorized.account.shouldBeServiceTaskMaster.set(.single(.never))
authorized.account.shouldKeepOnlinePresence.set(.single(false))
authorized.account.shouldExplicitelyKeepWorkerConnections.set(.single(false))
authorized.account.shouldKeepBackgroundDownloadConnections.set(.single(false))
authorized.context.isCurrent = false
authorized.context.account.shouldBeServiceTaskMaster.set(.single(.never))
authorized.context.account.shouldKeepOnlinePresence.set(.single(false))
authorized.context.account.shouldExplicitelyKeepWorkerConnections.set(.single(false))
authorized.context.account.shouldKeepBackgroundDownloadConnections.set(.single(false))
default:
break
}
}
self.contextValue = context
if let context = context {
(context.account?.applicationContext as? TelegramApplicationContext)?.isCurrent = true
updateLegacyComponentsAccount(context.account)
let isReady: Signal<Bool, NoError>
switch context {
case let .authorized(authorized):
setupLegacyComponents(context: authorized.context)
authorized.context.isCurrent = true
isReady = authorized.isReady.get()
default:
isReady = .single(true)
@@ -743,13 +742,11 @@ private enum QueuedWakeup: Int32 {
if #available(iOS 10.0, *) {
authorizeNotifications = false
}
self.registerForNotifications(account: context.account, authorize: authorizeNotifications)
context.account.notificationToken.set(self.notificationTokenPromise.get())
context.account.voipToken.set(self.voipTokenPromise.get())
self.registerForNotifications(context: context.context, authorize: authorizeNotifications)
context.context.account.notificationToken.set(self.notificationTokenPromise.get())
context.context.account.voipToken.set(self.voipTokenPromise.get())
case .unauthorized:
break
case .upgrading:
break
}
}))
} else {
@@ -780,8 +777,6 @@ private enum QueuedWakeup: Int32 {
return context.applicationBadge
case .unauthorized:
return .single(0)
case .upgrading:
return .single(0)
}
} else {
return .never()
@@ -797,12 +792,10 @@ private enum QueuedWakeup: Int32 {
if let context = context {
switch context {
case let .authorized(context):
let presentationData = context.account.telegramApplicationContext.currentPresentationData.with { $0 }
let presentationData = context.context.currentPresentationData.with { $0 }
return .single(applicationShortcutItems(strings: presentationData.strings))
case .unauthorized:
return .single([])
case .upgrading:
return .single([])
}
} else {
return .never()
@@ -853,7 +846,7 @@ private enum QueuedWakeup: Int32 {
}
if let contextValue = strongSelf.contextValue {
if case let .authorized(context) = contextValue {
let presentationData = context.applicationContext.currentPresentationData.with { $0 }
let presentationData = context.context.currentPresentationData.with { $0 }
strongSelf.mainWindow.present(standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: alert.title, text: alert.message ?? "", actions: actions), on: .root)
} else if case let .unauthorized(context) = contextValue {
strongSelf.mainWindow.present(standardTextAlertController(theme: AlertControllerTheme(authTheme: context.rootController.theme), title: alert.title, text: alert.message ?? "", actions: actions), on: .root)
@@ -1213,7 +1206,7 @@ private enum QueuedWakeup: Int32 {
|> take(1)
|> mapToSignal { context -> Signal<Void, NoError> in
if let context = context {
return context.account.postbox.transaction (ignoreDisabled: true, { transaction -> Void in
return context.context.account.postbox.transaction (ignoreDisabled: true, { transaction -> Void in
transaction.applyIncomingReadMaxId(readMessageId)
})
} else {
@@ -1228,7 +1221,7 @@ private enum QueuedWakeup: Int32 {
|> take(1)
|> mapToSignal { context -> Signal<Void, NoError> in
if let context = context {
context.account.network.mergeBackupDatacenterAddress(datacenterId: datacenterId, host: host, port: port, secret: secret)
context.context.account.network.mergeBackupDatacenterAddress(datacenterId: datacenterId, host: host, port: port, secret: secret)
}
return .complete()
}
@@ -1304,11 +1297,11 @@ private enum QueuedWakeup: Int32 {
case let .unauthorized(context):
if let proxyData = parseProxyUrl(url) {
context.rootController.view.endEditing(true)
let strings = context.applicationContext.currentPresentationData.with({ $0 }).strings
let strings = context.strings
let controller = ProxyServerActionSheetController(theme: defaultPresentationTheme, strings: strings, postbox: context.account.postbox, network: context.account.network, server: proxyData, presentationData: nil)
context.rootController.currentWindow?.present(controller, on: PresentationSurfaceLevel.root, blockInteraction: false, completion: {})
} else if let secureIdData = parseSecureIdUrl(url) {
let strings = context.applicationContext.currentPresentationData.with({ $0 }).strings
let strings = context.strings
let theme = context.rootController.theme
context.rootController.currentWindow?.present(standardTextAlertController(theme: AlertControllerTheme(authTheme: theme), title: nil, text: strings.Passport_NotLoggedInMessage, actions: [TextAlertAction(type: .genericAction, title: strings.Calls_NotNow, action: {
if let callbackUrl = URL(string: secureIdCallbackUrl(with: secureIdData.callbackUrl, peerId: secureIdData.peerId, result: .cancel, parameters: [:])) {
@@ -1331,7 +1324,7 @@ private enum QueuedWakeup: Int32 {
if let handle = contact.personHandle?.value {
if let userId = Int32(handle) {
if let contextValue = self.contextValue, case let .authorized(context) = contextValue {
let _ = context.applicationContext.callManager?.requestCall(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), endCurrentIfAny: false)
let _ = context.context.callManager?.requestCall(peerId: PeerId(namespace: Namespaces.Peer.CloudUser, id: userId), endCurrentIfAny: false)
}
}
}
@@ -1377,7 +1370,7 @@ private enum QueuedWakeup: Int32 {
case .camera:
context.openRootCamera()
case .savedMessages:
self.openChatWhenReady(peerId: context.account.peerId)
self.openChatWhenReady(peerId: context.context.account.peerId)
}
}
}
@@ -1396,9 +1389,8 @@ private enum QueuedWakeup: Int32 {
self.openUrlWhenReadyDisposable.set((self.authorizedContext()
|> take(1)
|> deliverOnMainQueue).start(next: { context in
let presentationData = context.account.telegramApplicationContext.currentPresentationData.with { $0 }
openExternalUrl(account: context.account, url: url, presentationData: presentationData, applicationContext: context.account.telegramApplicationContext, navigationController: context.rootController, dismissInput: {
let presentationData = context.context.currentPresentationData.with { $0 }
openExternalUrl(context: context.context, url: url, presentationData: presentationData, navigationController: context.rootController, dismissInput: {
})
}))
}
@@ -1423,9 +1415,9 @@ private enum QueuedWakeup: Int32 {
|> take(1)
|> mapToSignal { context -> Signal<Void, NoError> in
if let messageId = messageIdFromNotification(peerId: peerId, notification: response.notification) {
let _ = applyMaxReadIndexInteractively(postbox: context.account.postbox, stateManager: context.account.stateManager, index: MessageIndex(id: messageId, timestamp: 0)).start()
let _ = applyMaxReadIndexInteractively(postbox: context.context.account.postbox, stateManager: context.context.account.stateManager, index: MessageIndex(id: messageId, timestamp: 0)).start()
}
return enqueueMessages(account: context.account, peerId: peerId, messages: [EnqueueMessage.message(text: text, attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)])
return enqueueMessages(account: context.context.account, peerId: peerId, messages: [EnqueueMessage.message(text: text, attributes: [], mediaReference: nil, replyToMessageId: nil, localGroupingKey: nil)])
|> map { messageIds -> MessageId? in
if messageIds.isEmpty {
return nil
@@ -1435,7 +1427,7 @@ private enum QueuedWakeup: Int32 {
}
|> mapToSignal { messageId -> Signal<Void, NoError> in
if let messageId = messageId {
return context.account.postbox.unsentMessageIdsView()
return context.context.account.postbox.unsentMessageIdsView()
|> filter { view in
return !view.ids.contains(messageId)
}
@@ -1482,9 +1474,9 @@ private enum QueuedWakeup: Int32 {
}
}
private func registerForNotifications(account: Account, authorize: Bool = true, completion: @escaping (Bool) -> Void = { _ in }) {
let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 }
let _ = (account.postbox.transaction { transaction -> Bool in
private func registerForNotifications(context: AccountContext, authorize: Bool = true, completion: @escaping (Bool) -> Void = { _ in }) {
let presentationData = context.currentPresentationData.with { $0 }
let _ = (context.account.postbox.transaction { transaction -> Bool in
let settings = transaction.getPreferencesEntry(key: ApplicationSpecificPreferencesKeys.inAppNotificationSettings) as? InAppNotificationSettings ?? InAppNotificationSettings.defaultSettings
return settings.displayNameOnLockscreen
}
@@ -1559,7 +1551,7 @@ private enum QueuedWakeup: Int32 {
let queuedNotifications = self.queuedNotifications
self.queuedNotifications = []
for payload in queuedNotifications {
self.processPushPayload(payload, account: context.account)
self.processPushPayload(payload, account: context.context.account)
}
}
}
@@ -1571,7 +1563,7 @@ private enum QueuedWakeup: Int32 {
let queuedMutePolling = self.queuedMutePolling
self.queuedMutePolling = false
let _ = (context.account.postbox.transaction(ignoreDisabled: true, { transaction -> PostboxAccessChallengeData in
let _ = (context.context.account.postbox.transaction(ignoreDisabled: true, { transaction -> PostboxAccessChallengeData in
return transaction.getAccessChallengeData()
})
|> deliverOnMainQueue).start(next: { accessChallengeData in
@@ -1580,7 +1572,7 @@ private enum QueuedWakeup: Int32 {
return
}
let strings = context.account.telegramApplicationContext.currentPresentationData.with({ $0 }).strings
let strings = context.context.currentPresentationData.with({ $0 }).strings
for (title, body, apnsSound, requestId) in requests {
if handleVoipNotifications {
@@ -1620,9 +1612,9 @@ private enum QueuedWakeup: Int32 {
if let contextValue = self.contextValue, case let .authorized(context) = contextValue, !self.queuedAnnouncements.isEmpty {
let queuedAnnouncements = self.queuedAnnouncements
self.queuedAnnouncements = []
let _ = (context.account.postbox.transaction(ignoreDisabled: true, { transaction -> [MessageId: String] in
let _ = (context.context.account.postbox.transaction(ignoreDisabled: true, { transaction -> [MessageId: String] in
var result: [MessageId: String] = [:]
let timestamp = Int32(context.account.network.globalTime)
let timestamp = Int32(context.context.account.network.globalTime)
let servicePeer = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 777000), accessHash: nil, firstName: "Telegram", lastName: nil, username: nil, phone: "42777", photo: [], botInfo: nil, restrictionInfo: nil, flags: [.isVerified])
if transaction.getPeer(servicePeer.id) == nil {
transaction.updatePeersInternal([servicePeer], update: { _, updated in
@@ -1646,7 +1638,7 @@ private enum QueuedWakeup: Int32 {
}) |> deliverOnMainQueue).start(next: { result in
if let contextValue = self.contextValue, case let .authorized(context) = contextValue {
for (id, text) in result {
context.notificationManager.enqueueRemoteNotification(title: "", text: text, apnsSound: nil, requestId: .messageId(id), strings: context.account.telegramApplicationContext.currentPresentationData.with({ $0 }).strings, accessChallengeData: .none)
context.notificationManager.enqueueRemoteNotification(title: "", text: text, apnsSound: nil, requestId: .messageId(id), strings: context.context.currentPresentationData.with({ $0 }).strings, accessChallengeData: .none)
}
}
})
@@ -1663,7 +1655,7 @@ private enum QueuedWakeup: Int32 {
case .backgroundLocation:
if UIApplication.shared.applicationState == .background {
if let contextValue = self.contextValue, case let .authorized(context) = contextValue {
context.applicationContext.liveLocationManager?.pollOnce()
context.context.liveLocationManager?.pollOnce()
}
}
}
@@ -1682,7 +1674,7 @@ private enum QueuedWakeup: Int32 {
}
override var next: UIResponder? {
if let contextValue = self.contextValue, case let .authorized(context) = contextValue, let controller = context.applicationContext.keyShortcutsController {
if let contextValue = self.contextValue, case let .authorized(context) = contextValue, let controller = context.context.keyShortcutsController {
return controller
}
return super.next

View File

@@ -15,18 +15,18 @@ func applicationContext(networkArguments: NetworkInitializationArguments, applic
if let account = account {
switch account {
case .upgrading:
return .single(.upgrading(UpgradingApplicationContext()))
preconditionFailure()
case let .unauthorized(account):
return currentPresentationDataAndSettings(postbox: account.postbox)
|> deliverOnMainQueue
|> map { dataAndSettings -> ApplicationContext? in
return .unauthorized(UnauthorizedApplicationContext(applicationContext: TelegramApplicationContext(applicationBindings: applicationBindings, accountManager: accountManager, account: nil, initialPresentationDataAndSettings: dataAndSettings, postbox: account.postbox), account: account))
}
|> deliverOnMainQueue
|> map { dataAndSettings -> ApplicationContext? in
return .unauthorized(UnauthorizedApplicationContext(account: account, applicationBindings: applicationBindings))
}
case let .authorized(account):
return currentPresentationDataAndSettings(postbox: account.postbox)
|> deliverOnMainQueue
|> map { dataAndSettings -> ApplicationContext? in
return .authorized(AuthorizedApplicationContext(mainWindow: mainWindow, applicationContext: TelegramApplicationContext(applicationBindings: applicationBindings, accountManager: accountManager, account: account, initialPresentationDataAndSettings: dataAndSettings, postbox: account.postbox), replyFromNotificationsActive: replyFromNotificationsActive, backgroundAudioActive: backgroundAudioActive, watchManagerArguments: watchManagerArguments, account: account, accountManager: accountManager, legacyBasePath: legacyBasePath, showCallsTab: dataAndSettings.callListSettings.showTab, reinitializedNotificationSettings: reinitializedNotificationSettings))
|> deliverOnMainQueue
|> map { dataAndSettings -> ApplicationContext? in
return .authorized(AuthorizedApplicationContext(mainWindow: mainWindow, replyFromNotificationsActive: replyFromNotificationsActive, backgroundAudioActive: backgroundAudioActive, watchManagerArguments: watchManagerArguments, context: AccountContext(account: account, applicationBindings: applicationBindings, accountManager: accountManager, initialPresentationDataAndSettings: dataAndSettings, postbox: account.postbox), accountManager: accountManager, legacyBasePath: legacyBasePath, showCallsTab: dataAndSettings.callListSettings.showTab, reinitializedNotificationSettings: reinitializedNotificationSettings))
}
}
} else {
@@ -44,36 +44,29 @@ func isAccessLocked(data: PostboxAccessChallengeData, at timestamp: Int32) -> Bo
}
enum ApplicationContext {
case upgrading(UpgradingApplicationContext)
case unauthorized(UnauthorizedApplicationContext)
case authorized(AuthorizedApplicationContext)
var account: Account? {
switch self {
case .upgrading:
return nil
case .unauthorized:
return nil
case let .authorized(context):
return context.account
return context.context.account
}
}
var accountId: AccountRecordId? {
switch self {
case .upgrading:
return nil
case let .unauthorized(unauthorized):
return unauthorized.account.id
case let .authorized(authorized):
return authorized.account.id
return authorized.context.account.id
}
}
var rootController: NavigationController {
switch self {
case let .upgrading(context):
return context.rootController
case let .unauthorized(context):
return context.rootController
case let .authorized(context):
@@ -83,8 +76,6 @@ enum ApplicationContext {
var overlayControllers: [ViewController] {
switch self {
case .upgrading:
return []
case .unauthorized:
return []
case let .authorized(context):
@@ -93,32 +84,19 @@ enum ApplicationContext {
}
}
final class UpgradingApplicationContext {
let rootController: NavigationController
init() {
self.rootController = NavigationController(mode: .single, theme: NavigationControllerTheme(navigationBar: NavigationBarTheme(buttonColor: .white, disabledButtonColor: .gray, primaryTextColor: .white, backgroundColor: .black, separatorColor: .white, badgeBackgroundColor: .black, badgeStrokeColor: .black, badgeTextColor: .white), emptyAreaColor: .black, emptyDetailIcon: nil))
let noticeController = ViewController(navigationBarPresentationData: nil)
self.rootController.pushViewController(noticeController, animated: false)
}
}
final class UnauthorizedApplicationContext {
let applicationContext: TelegramApplicationContext
let account: UnauthorizedAccount
var strings: PresentationStrings
let rootController: AuthorizationSequenceController
init(applicationContext: TelegramApplicationContext, account: UnauthorizedAccount) {
init(account: UnauthorizedAccount, applicationBindings: TelegramApplicationBindings) {
self.account = account
self.applicationContext = applicationContext
self.strings = defaultPresentationStrings
self.rootController = AuthorizationSequenceController(account: account, strings: (applicationContext.currentPresentationData.with { $0 }).strings, openUrl: { [weak applicationContext] url in
applicationContext?.applicationBindings.openUrl(url)
}, apiId: BuildConfig.shared().apiId, apiHash: BuildConfig.shared().apiHash)
self.rootController = AuthorizationSequenceController(account: account, strings: self.strings, openUrl: applicationBindings.openUrl, apiId: BuildConfig.shared().apiId, apiHash: BuildConfig.shared().apiHash)
account.shouldBeServiceTaskMaster.set(applicationContext.applicationBindings.applicationInForeground |> map { value -> AccountServiceTaskMasterMode in
account.shouldBeServiceTaskMaster.set(applicationBindings.applicationInForeground |> map { value -> AccountServiceTaskMasterMode in
if value {
return .always
} else {
@@ -162,8 +140,7 @@ final class AuthorizedApplicationContext {
let mainWindow: Window1
let lockedCoveringView: LockedWindowCoveringView
let applicationContext: TelegramApplicationContext
let account: Account
let context: AccountContext
let replyFromNotificationsActive: Signal<Bool, NoError>
let backgroundAudioActive: Signal<Bool, NoError>
@@ -204,7 +181,7 @@ final class AuthorizedApplicationContext {
}
var applicationBadge: Signal<Int32, NoError> {
return renderedTotalUnreadCount(postbox: self.account.postbox)
return renderedTotalUnreadCount(postbox: self.context.account.postbox)
|> map {
$0.0
}
@@ -226,20 +203,19 @@ final class AuthorizedApplicationContext {
private var showCallsTabDisposable: Disposable?
private var enablePostboxTransactionsDiposable: Disposable?
init(mainWindow: Window1, applicationContext: TelegramApplicationContext, replyFromNotificationsActive: Signal<Bool, NoError>, backgroundAudioActive: Signal<Bool, NoError>, watchManagerArguments: Signal<WatchManagerArguments?, NoError>, account: Account, accountManager: AccountManager, legacyBasePath: String, showCallsTab: Bool, reinitializedNotificationSettings: @escaping () -> Void) {
setupLegacyComponents(account: account)
let presentationData = applicationContext.currentPresentationData.with { $0 }
init(mainWindow: Window1, replyFromNotificationsActive: Signal<Bool, NoError>, backgroundAudioActive: Signal<Bool, NoError>, watchManagerArguments: Signal<WatchManagerArguments?, NoError>, context: AccountContext, accountManager: AccountManager, legacyBasePath: String, showCallsTab: Bool, reinitializedNotificationSettings: @escaping () -> Void) {
setupLegacyComponents(context: context)
let presentationData = context.currentPresentationData.with { $0 }
self.mainWindow = mainWindow
self.lockedCoveringView = LockedWindowCoveringView(theme: presentationData.theme)
self.applicationContext = applicationContext
self.account = account
self.context = context
self.replyFromNotificationsActive = replyFromNotificationsActive
self.backgroundAudioActive = backgroundAudioActive
let runningBackgroundLocationTasks: Signal<Bool, NoError>
if let liveLocationManager = applicationContext.liveLocationManager {
if let liveLocationManager = context.liveLocationManager {
runningBackgroundLocationTasks = liveLocationManager.isPolling
} else {
runningBackgroundLocationTasks = .single(false)
@@ -248,7 +224,7 @@ final class AuthorizedApplicationContext {
let runningWatchTasksPromise = Promise<WatchRunningTasks?>(nil)
let downloadPreferencesKey = PostboxViewKey.preferences(keys: Set([ApplicationSpecificPreferencesKeys.automaticMediaDownloadSettings]))
let runningDownloadTasks = combineLatest(account.postbox.combinedView(keys: [downloadPreferencesKey]), account.shouldKeepBackgroundDownloadConnections.get())
let runningDownloadTasks = combineLatest(context.account.postbox.combinedView(keys: [downloadPreferencesKey]), context.account.shouldKeepBackgroundDownloadConnections.get())
|> map { views, shouldKeepBackgroundDownloadConnections -> Bool in
let settings: AutomaticMediaDownloadSettings = (views.views[downloadPreferencesKey] as? PreferencesView)?.values[ApplicationSpecificPreferencesKeys.automaticMediaDownloadSettings] as? AutomaticMediaDownloadSettings ?? AutomaticMediaDownloadSettings.defaultSettings
if !settings.downloadInBackground {
@@ -258,31 +234,31 @@ final class AuthorizedApplicationContext {
}
|> distinctUntilChanged
self.wakeupManager = WakeupManager(inForeground: applicationContext.applicationBindings.applicationInForeground, runningServiceTasks: account.importantTasksRunning, runningBackgroundLocationTasks: runningBackgroundLocationTasks, runningWatchTasks: runningWatchTasksPromise.get(), runningDownloadTasks: runningDownloadTasks)
self.wakeupManager.account = account
self.wakeupManager = WakeupManager(inForeground: context.applicationBindings.applicationInForeground, runningServiceTasks: context.account.importantTasksRunning, runningBackgroundLocationTasks: runningBackgroundLocationTasks, runningWatchTasks: runningWatchTasksPromise.get(), runningDownloadTasks: runningDownloadTasks)
self.wakeupManager.account = context.account
self.showCallsTab = showCallsTab
self.notificationManager = NotificationManager()
self.notificationManager.account = account
self.notificationManager.context = context
self.notificationManager.isApplicationInForeground = false
self.overlayMediaController = OverlayMediaController()
applicationContext.attachOverlayMediaController(self.overlayMediaController)
context.attachOverlayMediaController(self.overlayMediaController)
var presentImpl: ((ViewController, Any?) -> Void)?
var openSettingsImpl: (() -> Void)?
let callManager = PresentationCallManager(account: account, getDeviceAccessData: {
return (account.telegramApplicationContext.currentPresentationData.with { $0 }, { c, a in
let callManager = PresentationCallManager(account: context.account, getDeviceAccessData: {
return (context.currentPresentationData.with { $0 }, { c, a in
presentImpl?(c, a)
}, {
openSettingsImpl?()
})
}, networkType: account.networkType, audioSession: applicationContext.mediaManager!.audioSession, callSessionManager: account.callSessionManager)
applicationContext.callManager = callManager
applicationContext.hasOngoingCall = self.hasOngoingCall.get()
}, networkType: context.account.networkType, audioSession: context.mediaManager.audioSession, callSessionManager: context.account.callSessionManager)
context.callManager = callManager
context.hasOngoingCall = self.hasOngoingCall.get()
let shouldBeServiceTaskMaster = combineLatest(applicationContext.applicationBindings.applicationInForeground, self.wakeupManager.isWokenUp, replyFromNotificationsActive, backgroundAudioActive, callManager.hasActiveCalls)
let shouldBeServiceTaskMaster = combineLatest(context.applicationBindings.applicationInForeground, self.wakeupManager.isWokenUp, replyFromNotificationsActive, backgroundAudioActive, callManager.hasActiveCalls)
|> map { foreground, wokenUp, replyFromNotificationsActive, backgroundAudioActive, hasActiveCalls -> AccountServiceTaskMasterMode in
if foreground || wokenUp || replyFromNotificationsActive || hasActiveCalls {
return .always
@@ -290,7 +266,7 @@ final class AuthorizedApplicationContext {
return .never
}
}
account.shouldBeServiceTaskMaster.set(shouldBeServiceTaskMaster)
context.account.shouldBeServiceTaskMaster.set(shouldBeServiceTaskMaster)
self.enablePostboxTransactionsDiposable = (combineLatest(shouldBeServiceTaskMaster, backgroundAudioActive)
|> map { shouldBeServiceTaskMaster, backgroundAudioActive -> Bool in
switch shouldBeServiceTaskMaster {
@@ -304,31 +280,29 @@ final class AuthorizedApplicationContext {
}
return false
}
|> deliverOnMainQueue).start(next: { [weak account] next in
if let account = account {
|> deliverOnMainQueue).start(next: { [weak context] next in
if let context = context {
Logger.shared.log("ApplicationContext", "setting canBeginTransactions to \(next)")
account.postbox.setCanBeginTransactions(next)
context.account.postbox.setCanBeginTransactions(next)
}
})
account.shouldExplicitelyKeepWorkerConnections.set(backgroundAudioActive)
account.shouldKeepBackgroundDownloadConnections.set(applicationContext.fetchManager.hasUserInitiatedEntries)
account.shouldKeepOnlinePresence.set(applicationContext.applicationBindings.applicationInForeground)
context.account.shouldExplicitelyKeepWorkerConnections.set(backgroundAudioActive)
context.account.shouldKeepBackgroundDownloadConnections.set(context.fetchManager.hasUserInitiatedEntries)
context.account.shouldKeepOnlinePresence.set(context.applicationBindings.applicationInForeground)
let cache = TGCache(cachesPath: legacyBasePath + "/Caches")!
setupAccount(account, fetchCachedResourceRepresentation: fetchCachedResourceRepresentation, transformOutgoingMessageMedia: transformOutgoingMessageMedia, preFetchedResourcePath: { resource in
setupAccount(context.account, fetchCachedResourceRepresentation: fetchCachedResourceRepresentation, transformOutgoingMessageMedia: transformOutgoingMessageMedia, preFetchedResourcePath: { resource in
preFetchedLegacyResourcePath(basePath: legacyBasePath, resource: resource, cache: cache)
})
account.applicationContext = applicationContext
self.notificationController = NotificationContainerController(account: account)
self.notificationController = NotificationContainerController(context: context)
self.mainWindow.previewThemeAccentColor = presentationData.theme.rootController.navigationBar.accentTextColor
self.mainWindow.previewThemeDarkBlur = presentationData.theme.chatList.searchBarKeyboardColor == .dark
self.mainWindow.setupVolumeControlStatusBarGraphics(presentationData.volumeControlStatusBarIcons.images)
self.rootController = TelegramRootController(account: account)
self.rootController = TelegramRootController(context: context)
if KeyShortcutsController.isAvailable {
let keyShortcutsController = KeyShortcutsController { [weak self] f in
@@ -347,10 +321,10 @@ final class AuthorizedApplicationContext {
strongSelf.mainWindow.forEachViewController(f)
}
}
applicationContext.keyShortcutsController = keyShortcutsController
context.keyShortcutsController = keyShortcutsController
}
self.applicationInForegroundDisposable = applicationContext.applicationBindings.applicationInForeground.start(next: { [weak self] value in
self.applicationInForegroundDisposable = context.applicationBindings.applicationInForeground.start(next: { [weak self] value in
Queue.mainQueue().async {
self?.notificationManager.isApplicationInForeground = value
}
@@ -365,10 +339,10 @@ final class AuthorizedApplicationContext {
}
}
applicationContext.presentGlobalController = { [weak self] c, a in
context.presentGlobalController = { [weak self] c, a in
self?.mainWindow.present(c, on: .root)
}
applicationContext.presentCrossfadeController = { [weak self] in
context.presentCrossfadeController = { [weak self] in
guard let strongSelf = self else {
return
}
@@ -385,7 +359,7 @@ final class AuthorizedApplicationContext {
}
}
applicationContext.navigateToCurrentCall = { [weak self] in
context.navigateToCurrentCall = { [weak self] in
if let strongSelf = self, let callController = strongSelf.callController {
if callController.isNodeLoaded && callController.view.superview == nil {
strongSelf.rootController.view.endEditing(true)
@@ -397,15 +371,15 @@ final class AuthorizedApplicationContext {
presentImpl = { [weak self] c, _ in
self?.mainWindow.present(c, on: .root)
}
openSettingsImpl = {
applicationContext.applicationBindings.openSettings()
openSettingsImpl = { [weak context] in
context?.applicationBindings.openSettings()
}
let previousPasscodeState = Atomic<PasscodeState?>(value: nil)
let preferencesKey: PostboxViewKey = .preferences(keys: Set<ValueBoxKey>([ApplicationSpecificPreferencesKeys.presentationPasscodeSettings]))
self.passcodeStatusDisposable.set((combineLatest(queue: Queue.mainQueue(), account.postbox.combinedView(keys: [.accessChallengeData, preferencesKey]), applicationContext.applicationBindings.applicationIsActive)
self.passcodeStatusDisposable.set((combineLatest(queue: Queue.mainQueue(), context.account.postbox.combinedView(keys: [.accessChallengeData, preferencesKey]), context.applicationBindings.applicationIsActive)
|> map { view, isActive -> (PostboxAccessChallengeData, PresentationPasscodeSettings?, Bool) in
let accessChallengeData = (view.views[.accessChallengeData] as? AccessChallengeDataView)?.data ?? PostboxAccessChallengeData.none
let passcodeSettings = (view.views[preferencesKey] as! PreferencesView).values[ApplicationSpecificPreferencesKeys.presentationPasscodeSettings] as? PresentationPasscodeSettings
@@ -450,7 +424,7 @@ final class AuthorizedApplicationContext {
if previousState?.isActive != updatedState.isActive || isLocked != strongSelf.isLocked {
if updatedAutolockDeadline != previousState?.challengeData.autolockDeadline {
let _ = (account.postbox.transaction { transaction -> Void in
let _ = (strongSelf.context.account.postbox.transaction { transaction -> Void in
let data = transaction.getAccessChallengeData().withUpdatedAutolockDeadline(updatedAutolockDeadline)
transaction.setAccessChallengeData(data)
}).start()
@@ -475,12 +449,15 @@ final class AuthorizedApplicationContext {
case .plaintextPassword:
mode = TGPasscodeEntryControllerModeVerifyComplex
}
let presentationData = strongSelf.account.telegramApplicationContext.currentPresentationData.with { $0 }
let presentationData = strongSelf.context.currentPresentationData.with { $0 }
let presentAnimated = previousState != nil && previousState!.isActive
let legacyController = LegacyController(presentation: LegacyControllerPresentation.modal(animateIn: presentAnimated), theme: presentationData.theme)
let controller = TGPasscodeEntryController(context: legacyController.context, style: TGPasscodeEntryControllerStyleDefault, mode: mode, cancelEnabled: false, allowTouchId: updatedState.enableBiometrics, attemptData: attemptData, completion: { value in
guard let strongSelf = self else {
return
}
if value != nil {
let _ = (account.postbox.transaction { transaction -> Void in
let _ = (strongSelf.context.account.postbox.transaction { transaction -> Void in
let data = transaction.getAccessChallengeData().withUpdatedAutolockDeadline(nil)
transaction.setAccessChallengeData(data)
}).start()
@@ -501,7 +478,10 @@ final class AuthorizedApplicationContext {
}
}
controller.updateAttemptData = { attemptData in
let _ = account.postbox.transaction({ transaction -> Void in
guard let strongSelf = self else {
return
}
let _ = strongSelf.context.account.postbox.transaction({ transaction -> Void in
var attempts: AccessChallengeAttempts?
if let attemptData = attemptData {
attempts = AccessChallengeAttempts(count: Int32(attemptData.numberOfInvalidAttempts), timestamp: Int32(attemptData.dateOfLastInvalidAttempt))
@@ -519,7 +499,10 @@ final class AuthorizedApplicationContext {
}).start()
}
controller.touchIdCompletion = {
let _ = (account.postbox.transaction { transaction -> Void in
guard let strongSelf = self else {
return
}
let _ = (strongSelf.context.account.postbox.transaction { transaction -> Void in
let data = transaction.getAccessChallengeData().withUpdatedAutolockDeadline(nil)
transaction.setAccessChallengeData(data)
}).start()
@@ -591,7 +574,7 @@ final class AuthorizedApplicationContext {
if #available(iOS 10.0, *) {
} else {
DeviceAccess.authorizeAccess(to: .contacts, presentationData: strongSelf.account.telegramApplicationContext.currentPresentationData.with { $0 }, present: { c, a in
DeviceAccess.authorizeAccess(to: .contacts, presentationData: strongSelf.context.currentPresentationData.with { $0 }, present: { c, a in
}, openSettings: {}, { _ in })
}
@@ -628,8 +611,8 @@ final class AuthorizedApplicationContext {
strongSelf.isReady.set(true)
}))
let accountId = account.id
self.loggedOutDisposable.set(account.loggedOut.start(next: { value in
let accountId = context.account.id
self.loggedOutDisposable.set(context.account.loggedOut.start(next: { value in
if value {
Logger.shared.log("ApplicationContext", "account logged out")
let _ = logoutFromAccount(id: accountId, accountManager: accountManager).start()
@@ -637,7 +620,7 @@ final class AuthorizedApplicationContext {
}))
let inAppPreferencesKey = PostboxViewKey.preferences(keys: Set([ApplicationSpecificPreferencesKeys.inAppNotificationSettings]))
self.inAppNotificationSettingsDisposable.set(((account.postbox.combinedView(keys: [inAppPreferencesKey])) |> deliverOnMainQueue).start(next: { [weak self] views in
self.inAppNotificationSettingsDisposable.set(((context.account.postbox.combinedView(keys: [inAppPreferencesKey])) |> deliverOnMainQueue).start(next: { [weak self] views in
if let strongSelf = self {
if let view = views.views[inAppPreferencesKey] as? PreferencesView {
if let settings = view.values[ApplicationSpecificPreferencesKeys.inAppNotificationSettings] as? InAppNotificationSettings {
@@ -651,7 +634,8 @@ final class AuthorizedApplicationContext {
}
}))
self.notificationMessagesDisposable.set((account.stateManager.notificationMessages |> deliverOn(Queue.mainQueue())).start(next: { [weak self] messageList in
self.notificationMessagesDisposable.set((context.account.stateManager.notificationMessages
|> deliverOn(Queue.mainQueue())).start(next: { [weak self] messageList in
if let strongSelf = self, let (messages, groupId, notify) = messageList.last, let firstMessage = messages.first {
if UIApplication.shared.applicationState == .active {
var chatIsVisible = false
@@ -698,8 +682,8 @@ final class AuthorizedApplicationContext {
}
if inAppNotificationSettings.displayPreviews {
let presentationData = strongSelf.applicationContext.currentPresentationData.with { $0 }
strongSelf.notificationController.enqueue(ChatMessageNotificationItem(account: strongSelf.account, strings: presentationData.strings, nameDisplayOrder: presentationData.nameDisplayOrder, messages: messages, tapAction: {
let presentationData = strongSelf.context.currentPresentationData.with { $0 }
strongSelf.notificationController.enqueue(ChatMessageNotificationItem(context: strongSelf.context, strings: presentationData.strings, nameDisplayOrder: presentationData.nameDisplayOrder, messages: messages, tapAction: {
if let strongSelf = self {
var foundOverlay = false
strongSelf.mainWindow.forEachViewController({ controller in
@@ -732,12 +716,12 @@ final class AuthorizedApplicationContext {
strongSelf.notificationController.removeItemsWithGroupingKey(firstMessage.id.peerId)
navigateToChatController(navigationController: strongSelf.rootController, account: strongSelf.account, chatLocation: .peer(firstMessage.id.peerId))
navigateToChatController(navigationController: strongSelf.rootController, context: strongSelf.context, chatLocation: .peer(firstMessage.id.peerId))
}
return false
}, expandAction: { expandData in
if let strongSelf = self {
let chatController = ChatController(account: strongSelf.account, chatLocation: .peer(firstMessage.id.peerId), mode: .overlay)
let chatController = ChatController(context: strongSelf.context, chatLocation: .peer(firstMessage.id.peerId), mode: .overlay)
(strongSelf.rootController.viewControllers.last as? ViewController)?.present(chatController, in: .window(.root), with: ChatControllerOverlayPresentationData(expandData: expandData()))
}
}))
@@ -746,7 +730,7 @@ final class AuthorizedApplicationContext {
}
}))
self.termsOfServiceUpdatesDisposable.set((account.stateManager.termsOfServiceUpdate
self.termsOfServiceUpdatesDisposable.set((context.account.stateManager.termsOfServiceUpdate
|> deliverOnMainQueue).start(next: { [weak self] termsOfServiceUpdate in
guard let strongSelf = self, strongSelf.currentTermsOfServiceUpdate != termsOfServiceUpdate else {
return
@@ -754,7 +738,7 @@ final class AuthorizedApplicationContext {
strongSelf.currentTermsOfServiceUpdate = termsOfServiceUpdate
if let termsOfServiceUpdate = termsOfServiceUpdate {
let presentationData = strongSelf.applicationContext.currentPresentationData.with { $0 }
let presentationData = strongSelf.context.currentPresentationData.with { $0 }
var acceptImpl: ((String?) -> Void)?
var declineImpl: (() -> Void)?
let controller = TermsOfServiceController(theme: TermsOfServiceControllerTheme(presentationTheme: presentationData.theme), strings: presentationData.strings, text: termsOfServiceUpdate.text, entities: termsOfServiceUpdate.entities, ageConfirmation: termsOfServiceUpdate.ageConfirmation, signingUp: false, accept: { proccedBot in
@@ -772,13 +756,13 @@ final class AuthorizedApplicationContext {
guard let strongSelf = self else {
return
}
let _ = (acceptTermsOfService(account: strongSelf.account, id: termsOfServiceUpdate.id)
let _ = (acceptTermsOfService(account: strongSelf.context.account, id: termsOfServiceUpdate.id)
|> deliverOnMainQueue).start(completed: {
controller?.dismiss()
if let botName = botName {
self?.termsOfServiceProceedToBotDisposable.set((resolvePeerByName(account: account, name: botName, ageLimit: 10) |> take(1) |> deliverOnMainQueue).start(next: { peerId in
if let peerId = peerId {
self?.rootController.pushViewController(ChatController(account: account, chatLocation: .peer(peerId), messageId: nil))
if let strongSelf = self, let botName = botName {
strongSelf.termsOfServiceProceedToBotDisposable.set((resolvePeerByName(account: strongSelf.context.account, name: botName, ageLimit: 10) |> take(1) |> deliverOnMainQueue).start(next: { peerId in
if let strongSelf = self, let peerId = peerId {
self?.rootController.pushViewController(ChatController(context: strongSelf.context, chatLocation: .peer(peerId), messageId: nil))
}
}))
}
@@ -789,7 +773,7 @@ final class AuthorizedApplicationContext {
guard let strongSelf = self else {
return
}
let _ = (strongSelf.account.postbox.loadedPeerWithId(strongSelf.account.peerId)
let _ = (strongSelf.context.account.postbox.loadedPeerWithId(strongSelf.context.account.peerId)
|> deliverOnMainQueue).start(next: { peer in
if let phone = (peer as? TelegramUser)?.phone {
UIApplication.shared.openURL(URL(string: "https://telegram.org/deactivate?phone=\(phone)")!)
@@ -805,7 +789,7 @@ final class AuthorizedApplicationContext {
let debugModal = false
let permissionsPosition = ValuePromise(0, ignoreRepeated: true)
self.permissionsDisposable.set((combineLatest(requiredPermissions(account: account), permissionUISplitTest(postbox: account.postbox), permissionsPosition.get(), account.postbox.combinedView(keys: [.noticeEntry(ApplicationSpecificNotice.contactsPermissionWarningKey()), .noticeEntry(ApplicationSpecificNotice.notificationsPermissionWarningKey())]))
self.permissionsDisposable.set((combineLatest(requiredPermissions(context: context), permissionUISplitTest(postbox: context.account.postbox), permissionsPosition.get(), context.account.postbox.combinedView(keys: [.noticeEntry(ApplicationSpecificNotice.contactsPermissionWarningKey()), .noticeEntry(ApplicationSpecificNotice.notificationsPermissionWarningKey())]))
|> deliverOnMainQueue).start(next: { [weak self] required, splitTest, position, combined in
guard let strongSelf = self else {
return
@@ -814,10 +798,10 @@ final class AuthorizedApplicationContext {
let contactsTimestamp = (combined.views[.noticeEntry(ApplicationSpecificNotice.contactsPermissionWarningKey())] as? NoticeEntryView)?.value.flatMap({ ApplicationSpecificNotice.getTimestampValue($0) })
let notificationsTimestamp = (combined.views[.noticeEntry(ApplicationSpecificNotice.notificationsPermissionWarningKey())] as? NoticeEntryView)?.value.flatMap({ ApplicationSpecificNotice.getTimestampValue($0) })
if contactsTimestamp == nil, case .requestable = required.0.status {
ApplicationSpecificNotice.setContactsPermissionWarning(postbox: account.postbox, value: 1)
ApplicationSpecificNotice.setContactsPermissionWarning(postbox: context.account.postbox, value: 1)
}
if notificationsTimestamp == nil, case .requestable = required.1.status {
ApplicationSpecificNotice.setNotificationsPermissionWarning(postbox: account.postbox, value: 1)
ApplicationSpecificNotice.setNotificationsPermissionWarning(postbox: context.account.postbox, value: 1)
}
let config = splitTest.configuration
@@ -866,7 +850,7 @@ final class AuthorizedApplicationContext {
controller = currentController
didAppear = true
} else {
controller = PermissionController(account: account, splitTest: splitTest)
controller = PermissionController(context: context, splitTest: splitTest)
strongSelf.currentPermissionsController = controller
}
@@ -875,9 +859,9 @@ final class AuthorizedApplicationContext {
permissionsPosition.set(position + 1)
switch state {
case .contacts:
ApplicationSpecificNotice.setContactsPermissionWarning(postbox: account.postbox, value: 0)
ApplicationSpecificNotice.setContactsPermissionWarning(postbox: context.account.postbox, value: 0)
case .notifications:
ApplicationSpecificNotice.setNotificationsPermissionWarning(postbox: account.postbox, value: 0)
ApplicationSpecificNotice.setNotificationsPermissionWarning(postbox: context.account.postbox, value: 0)
default:
break
}
@@ -892,28 +876,28 @@ final class AuthorizedApplicationContext {
switch state {
case .contacts:
splitTest.addEvent(.ContactsRequest)
DeviceAccess.authorizeAccess(to: .contacts, account: account) { result in
DeviceAccess.authorizeAccess(to: .contacts, context: context) { result in
if result {
splitTest.addEvent(.ContactsAllowed)
} else {
splitTest.addEvent(.ContactsDenied)
}
permissionsPosition.set(position + 1)
ApplicationSpecificNotice.setContactsPermissionWarning(postbox: account.postbox, value: 0)
ApplicationSpecificNotice.setContactsPermissionWarning(postbox: context.account.postbox, value: 0)
}
case .notifications:
splitTest.addEvent(.NotificationsRequest)
DeviceAccess.authorizeAccess(to: .notifications, account: account) { result in
DeviceAccess.authorizeAccess(to: .notifications, context: context) { result in
if result {
splitTest.addEvent(.NotificationsAllowed)
} else {
splitTest.addEvent(.NotificationsDenied)
}
permissionsPosition.set(position + 1)
ApplicationSpecificNotice.setNotificationsPermissionWarning(postbox: account.postbox, value: 0)
ApplicationSpecificNotice.setNotificationsPermissionWarning(postbox: context.account.postbox, value: 0)
}
case .siri:
DeviceAccess.authorizeAccess(to: .siri, account: account) { result in
DeviceAccess.authorizeAccess(to: .siri, context: context) { result in
permissionsPosition.set(position + 1)
}
default:
@@ -929,20 +913,20 @@ final class AuthorizedApplicationContext {
}))
}
self.displayAlertsDisposable = (account.stateManager.displayAlerts |> deliverOnMainQueue).start(next: { [weak self] alerts in
self.displayAlertsDisposable = (context.account.stateManager.displayAlerts |> deliverOnMainQueue).start(next: { [weak self] alerts in
if let strongSelf = self{
for text in alerts {
let presentationData = strongSelf.applicationContext.currentPresentationData.with { $0 }
let presentationData = strongSelf.context.currentPresentationData.with { $0 }
let controller = standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: nil, text: text, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_OK, action: {})])
(strongSelf.rootController.viewControllers.last as? ViewController)?.present(controller, in: .window(.root))
}
}
})
self.removeNotificationsDisposable = (account.stateManager.appliedIncomingReadMessages
self.removeNotificationsDisposable = (context.account.stateManager.appliedIncomingReadMessages
|> deliverOnMainQueue).start(next: { [weak self] ids in
if let strongSelf = self {
strongSelf.applicationContext.applicationBindings.clearMessageNotifications(ids)
strongSelf.context.applicationBindings.clearMessageNotifications(ids)
}
})
@@ -955,7 +939,7 @@ final class AuthorizedApplicationContext {
strongSelf.hasOngoingCall.set(false)
if let call = call {
let callController = CallController(account: account, call: call)
let callController = CallController(context: strongSelf.context, call: call)
strongSelf.callController = callController
strongSelf.rootController.view?.endEditing(true)
strongSelf.mainWindow.present(callController, on: .calls)
@@ -1017,11 +1001,11 @@ final class AuthorizedApplicationContext {
}
})
self.account.resetStateManagement()
self.context.account.resetStateManagement()
let contactSynchronizationPreferencesKey = PostboxViewKey.preferences(keys: Set([ApplicationSpecificPreferencesKeys.contactSynchronizationSettings]))
let importableContacts = self.applicationContext.contactDataManager.importable()
self.account.importableContacts.set(self.account.postbox.combinedView(keys: [contactSynchronizationPreferencesKey])
let importableContacts = self.context.contactDataManager.importable()
self.context.account.importableContacts.set(self.context.account.postbox.combinedView(keys: [contactSynchronizationPreferencesKey])
|> mapToSignal { preferences -> Signal<[DeviceContactNormalizedPhoneNumber: ImportableDeviceContactData], NoError> in
let settings: ContactSynchronizationSettings = ((preferences.views[contactSynchronizationPreferencesKey] as? PreferencesView)?.values[ApplicationSpecificPreferencesKeys.contactSynchronizationSettings] as? ContactSynchronizationSettings) ?? .defaultSettings
if settings.synchronizeDeviceContacts {
@@ -1032,26 +1016,26 @@ final class AuthorizedApplicationContext {
})
let previousTheme = Atomic<PresentationTheme?>(value: nil)
self.presentationDataDisposable = (applicationContext.presentationData
|> deliverOnMainQueue).start(next: { [weak self] presentationData in
if let strongSelf = self {
if previousTheme.swap(presentationData.theme) !== presentationData.theme {
strongSelf.mainWindow.previewThemeAccentColor = presentationData.theme.rootController.navigationBar.accentTextColor
strongSelf.mainWindow.previewThemeDarkBlur = presentationData.theme.chatList.searchBarKeyboardColor == .dark
strongSelf.lockedCoveringView.updateTheme(presentationData.theme)
strongSelf.rootController.updateTheme(NavigationControllerTheme(presentationTheme: presentationData.theme))
}
self.presentationDataDisposable = (context.presentationData
|> deliverOnMainQueue).start(next: { [weak self] presentationData in
if let strongSelf = self {
if previousTheme.swap(presentationData.theme) !== presentationData.theme {
strongSelf.mainWindow.previewThemeAccentColor = presentationData.theme.rootController.navigationBar.accentTextColor
strongSelf.mainWindow.previewThemeDarkBlur = presentationData.theme.chatList.searchBarKeyboardColor == .dark
strongSelf.lockedCoveringView.updateTheme(presentationData.theme)
strongSelf.rootController.updateTheme(NavigationControllerTheme(presentationTheme: presentationData.theme))
}
})
let showCallsTabSignal = account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.callListSettings])
|> map { view -> Bool in
var value = true
if let settings = view.values[ApplicationSpecificPreferencesKeys.callListSettings] as? CallListSettings {
value = settings.showTab
}
return value
}
})
let showCallsTabSignal = context.account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.callListSettings])
|> map { view -> Bool in
var value = true
if let settings = view.values[ApplicationSpecificPreferencesKeys.callListSettings] as? CallListSettings {
value = settings.showTab
}
return value
}
self.showCallsTabDisposable = (showCallsTabSignal |> deliverOnMainQueue).start(next: { [weak self] value in
if let strongSelf = self {
if strongSelf.showCallsTab != value {
@@ -1067,10 +1051,10 @@ final class AuthorizedApplicationContext {
}
let watchManager = WatchManager(arguments: arguments)
strongSelf.applicationContext.watchManager = watchManager
strongSelf.context.watchManager = watchManager
runningWatchTasksPromise.set(watchManager.runningTasks)
strongSelf.watchNavigateToMessageDisposable.set((strongSelf.applicationContext.applicationBindings.applicationInForeground |> mapToSignal({ applicationInForeground -> Signal<(Bool, MessageId), NoError> in
strongSelf.watchNavigateToMessageDisposable.set((strongSelf.context.applicationBindings.applicationInForeground |> mapToSignal({ applicationInForeground -> Signal<(Bool, MessageId), NoError> in
return watchManager.navigateToMessageRequested
|> map { messageId in
return (applicationInForeground, messageId)
@@ -1085,13 +1069,13 @@ final class AuthorizedApplicationContext {
}
let navigateToMessage = {
navigateToChatController(navigationController: strongSelf.rootController, account: strongSelf.account, chatLocation: .peer(messageId.peerId), messageId: messageId)
navigateToChatController(navigationController: strongSelf.rootController, context: strongSelf.context, chatLocation: .peer(messageId.peerId), messageId: messageId)
}
if chatIsVisible {
navigateToMessage()
} else {
let presentationData = strongSelf.applicationContext.currentPresentationData.with { $0 }
let presentationData = strongSelf.context.currentPresentationData.with { $0 }
let controller = standardTextAlertController(theme: AlertControllerTheme(presentationTheme: presentationData.theme), title: presentationData.strings.WatchRemote_AlertTitle, text: presentationData.strings.WatchRemote_AlertText, actions: [TextAlertAction(type: .defaultAction, title: presentationData.strings.Common_Cancel, action: {}), TextAlertAction(type: .genericAction, title: presentationData.strings.WatchRemote_AlertOpen, action:navigateToMessage)])
(strongSelf.rootController.viewControllers.last as? ViewController)?.present(controller, in: .window(.root))
}
@@ -1106,7 +1090,7 @@ final class AuthorizedApplicationContext {
private func updateStatusBarText() {
if case let .inProgress(timestamp) = self.currentCallStatusText {
let text: String
let presentationData = self.applicationContext.currentPresentationData.with { $0 }
let presentationData = self.context.currentPresentationData.with { $0 }
if let timestamp = timestamp {
let duration = Int32(CFAbsoluteTimeGetCurrent() - timestamp)
let durationString: String
@@ -1128,9 +1112,9 @@ final class AuthorizedApplicationContext {
}
deinit {
self.account.postbox.clearCaches()
self.account.shouldKeepOnlinePresence.set(.single(false))
self.account.shouldBeServiceTaskMaster.set(.single(.never))
self.context.account.postbox.clearCaches()
self.context.account.shouldKeepOnlinePresence.set(.single(false))
self.context.account.shouldBeServiceTaskMaster.set(.single(.never))
self.loggedOutDisposable.dispose()
self.inAppNotificationSettingsDisposable.dispose()
self.notificationMessagesDisposable.dispose()
@@ -1157,7 +1141,7 @@ final class AuthorizedApplicationContext {
if visiblePeerId != peerId || messageId != nil {
if self.rootController.rootTabController != nil {
navigateToChatController(navigationController: self.rootController, account: self.account, chatLocation: .peer(peerId), messageId: messageId)
navigateToChatController(navigationController: self.rootController, context: self.context, chatLocation: .peer(peerId), messageId: messageId)
} else {
self.scheduledOperChatWithPeerId = peerId
}
@@ -1166,8 +1150,8 @@ final class AuthorizedApplicationContext {
func openUrl(_ url: URL) {
if self.rootController.rootTabController != nil {
let presentationData = self.account.telegramApplicationContext.currentPresentationData.with { $0 }
openExternalUrl(account: self.account, url: url.absoluteString, presentationData: presentationData, applicationContext: self.applicationContext, navigationController: self.rootController, dismissInput: { [weak self] in
let presentationData = self.context.currentPresentationData.with { $0 }
openExternalUrl(context: self.context, url: url.absoluteString, presentationData: presentationData, navigationController: self.rootController, dismissInput: { [weak self] in
self?.rootController.view.endEditing(true)
})
} else {

View File

@@ -83,12 +83,12 @@ private func processedSoundName(_ name: String) -> String {
final class NotificationManager {
private var processedMessages = Set<MessageId>()
var account: Account? {
var context: AccountContext? {
didSet {
assert(Queue.mainQueue().isCurrent())
if let account = self.account {
self.notificationMessagesDisposable.set((account.stateManager.notificationMessages
if let context = self.context {
self.notificationMessagesDisposable.set((context.account.stateManager.notificationMessages
|> deliverOn(Queue.mainQueue())).start(next: { [weak self] messages in
guard let strongSelf = self else {
return
@@ -265,8 +265,8 @@ final class NotificationManager {
}
func commitRemoteNotification(originalRequestId: NotificationManagedNotificationRequestId?, messageIds: [MessageId]) -> Signal<Void, NoError> {
if let account = self.account {
return account.postbox.transaction { transaction -> ([(MessageId, [Message], Bool, PeerMessageSound, Bool)], Bool) in
if let context = self.context {
return context.account.postbox.transaction { transaction -> ([(MessageId, [Message], Bool, PeerMessageSound, Bool)], Bool) in
var isLocked = false
if isAccessLocked(data: transaction.getAccessChallengeData(), at: Int32(CFAbsoluteTimeGetCurrent())) {
isLocked = true
@@ -304,7 +304,7 @@ final class NotificationManager {
|> beforeNext {
[weak self] results, isLocked in
if let strongSelf = self {
let delayUntilTimestamp: Int32 = strongSelf.account?.stateManager.getDelayNotificatonsUntil() ?? 0
let delayUntilTimestamp: Int32 = strongSelf.context?.account.stateManager.getDelayNotificatonsUntil() ?? 0
for (id, messages, notify, sound, displayContents) in results {
let requestId: NotificationManagedNotificationRequestId = .messageId(id)
@@ -352,11 +352,11 @@ final class NotificationManager {
}
private func processNotificationMessages(_ messageList: [([Message], PeerMessageSound, Bool, Bool)], isLocked: Bool) {
guard let account = self.account else {
Logger.shared.log("NotificationManager", "account missing")
guard let context = self.context else {
Logger.shared.log("NotificationManager", "context missing")
return
}
let presentationData = (account.telegramApplicationContext.currentPresentationData.with { $0 })
let presentationData = (context.currentPresentationData.with { $0 })
let strings = presentationData.strings
let nameDisplayOrder = presentationData.nameDisplayOrder
@@ -446,9 +446,9 @@ final class NotificationManager {
}
}
} else if messages[0].groupingKey != nil {
var kind = messageContentKind(messages[0], strings: strings, nameDisplayOrder: nameDisplayOrder, accountPeerId: account.peerId).key
var kind = messageContentKind(messages[0], strings: strings, nameDisplayOrder: nameDisplayOrder, accountPeerId: context.account.peerId).key
for i in 1 ..< messages.count {
let nextKind = messageContentKind(messages[i], strings: strings, nameDisplayOrder: nameDisplayOrder, accountPeerId: account.peerId)
let nextKind = messageContentKind(messages[i], strings: strings, nameDisplayOrder: nameDisplayOrder, accountPeerId: context.account.peerId)
if kind != nextKind.key {
kind = .text
break
@@ -548,21 +548,21 @@ final class NotificationManager {
title = nil
}
let chatPeer = RenderedPeer(peerId: firstMessage.id.peerId, peers: additionalPeers)
let (_, _, messageText) = chatListItemStrings(strings: strings, nameDisplayOrder: nameDisplayOrder, message: firstMessage, chatPeer: chatPeer, accountPeerId: account.peerId)
let (_, _, messageText) = chatListItemStrings(strings: strings, nameDisplayOrder: nameDisplayOrder, message: firstMessage, chatPeer: chatPeer, accountPeerId: context.account.peerId)
body = messageText
loop: for media in firstMessage.media {
if let image = media as? TelegramMediaImage {
mediaRepresentations = image.representations
if !firstMessage.containsSecretMedia, let account = self.account, let smallest = smallestImageRepresentation(image.representations), let largest = largestImageRepresentation(image.representations) {
if !firstMessage.containsSecretMedia, let context = self.context, let smallest = smallestImageRepresentation(image.representations), let largest = largestImageRepresentation(image.representations) {
var imageInfo: [String: Any] = [:]
var thumbnailInfo: [String: Any] = [:]
thumbnailInfo["path"] = account.postbox.mediaBox.resourcePath(smallest.resource)
thumbnailInfo["path"] = context.account.postbox.mediaBox.resourcePath(smallest.resource)
imageInfo["thumbnail"] = thumbnailInfo
var fullSizeInfo: [String: Any] = [:]
fullSizeInfo["path"] = account.postbox.mediaBox.resourcePath(largest.resource)
fullSizeInfo["path"] = context.account.postbox.mediaBox.resourcePath(largest.resource)
imageInfo["fullSize"] = fullSizeInfo
imageInfo["width"] = Int(largest.dimensions.width)
@@ -675,7 +675,7 @@ final class NotificationManager {
content.threadIdentifier = "peer_\(firstMessage.id.peerId.toInt64())"
if mediaInfo != nil, let mediaRepresentations = mediaRepresentations {
if let account = self.account, let smallest = smallestImageRepresentation(mediaRepresentations) {
if let context = self.context, let smallest = smallestImageRepresentation(mediaRepresentations) {
/*if let path = account.postbox.mediaBox.completedResourcePath(smallest.resource) {
var randomId: Int64 = 0
arc4random_buf(&randomId, 8)
@@ -769,10 +769,10 @@ final class NotificationManager {
}
self.currentNotificationCall = call
guard let account = self.account else {
guard let context = self.context else {
return
}
let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 }
let presentationData = context.currentPresentationData.with { $0 }
if let notificationCall = call {
if #available(iOS 10.0, *) {
let content = UNMutableNotificationContent()
@@ -815,10 +815,10 @@ final class NotificationManager {
}
}
}
guard let account = self.account else {
guard let context = self.context else {
return
}
let presentationData = account.telegramApplicationContext.currentPresentationData.with { $0 }
let presentationData = context.currentPresentationData.with { $0 }
var userInfo: [AnyHashable : Any] = [:]
userInfo["peerId"] = messageId.peerId.toInt64()

View File

@@ -8,25 +8,25 @@ import Display
import TelegramUI
func snapshotAppearanceSettings(application: UIApplication, mainWindow: UIWindow, window: Window1, statusBarHost: StatusBarHost) {
let (account, _) = snapshotEnvironment(application: application, mainWindow: mainWindow, statusBarHost: statusBarHost, theme: .day)
account.network.mockConnectionStatus = .online(proxyAddress: nil)
let (context, accountManager) = snapshotEnvironment(application: application, mainWindow: mainWindow, statusBarHost: statusBarHost, theme: .day)
context.account.network.mockConnectionStatus = .online(proxyAddress: nil)
let _ = (account.postbox.transaction { transaction -> Void in
if let hole = account.postbox.seedConfiguration.initializeChatListWithHole.topLevel {
let _ = (context.account.postbox.transaction { transaction -> Void in
if let hole = context.account.postbox.seedConfiguration.initializeChatListWithHole.topLevel {
transaction.replaceChatListHole(groupId: nil, index: hole.index, hole: nil)
}
let accountPeer = TelegramUser(id: account.peerId, accessHash: nil, firstName: "Alena", lastName: "Shy", username: "alenashy", phone: "44321456789", photo: snapshotAvatar(account.postbox, 1), botInfo: nil, restrictionInfo: nil, flags: [])
let accountPeer = TelegramUser(id: context.account.peerId, accessHash: nil, firstName: "Alena", lastName: "Shy", username: "alenashy", phone: "44321456789", photo: snapshotAvatar(context.account.postbox, 1), botInfo: nil, restrictionInfo: nil, flags: [])
transaction.updatePeersInternal([accountPeer], update: { _, updated in
return updated
})
}).start()
let rootController = TelegramRootController(account: account)
let rootController = TelegramRootController(context: context)
rootController.addRootControllers(showCallsTab: true)
window.viewController = rootController
rootController.rootTabController!.selectedIndex = 3
rootController.pushViewController(themeSettingsController(account: account))
rootController.pushViewController(themeSettingsController(context: context))
}
#endif

View File

@@ -108,33 +108,33 @@ private let chatList: [SnapshotChat] = [
]
func snapshotChatList(application: UIApplication, mainWindow: UIWindow, window: Window1, statusBarHost: StatusBarHost) {
let (account, _) = snapshotEnvironment(application: application, mainWindow: mainWindow, statusBarHost: statusBarHost, theme: .night)
account.network.mockConnectionStatus = .online(proxyAddress: nil)
let (context, _) = snapshotEnvironment(application: application, mainWindow: mainWindow, statusBarHost: statusBarHost, theme: .night)
context.account.network.mockConnectionStatus = .online(proxyAddress: nil)
let _ = (account.postbox.transaction { transaction -> Void in
if let hole = account.postbox.seedConfiguration.initializeChatListWithHole.topLevel {
let _ = (context.account.postbox.transaction { transaction -> Void in
if let hole = context.account.postbox.seedConfiguration.initializeChatListWithHole.topLevel {
transaction.replaceChatListHole(groupId: nil, index: hole.index, hole: nil)
}
let accountPeer = TelegramUser(id: account.peerId, accessHash: nil, firstName: "Alena", lastName: "Shy", username: "alenashy", phone: "44321456789", photo: [], botInfo: nil, restrictionInfo: nil, flags: [])
let accountPeer = TelegramUser(id: context.account.peerId, accessHash: nil, firstName: "Alena", lastName: "Shy", username: "alenashy", phone: "44321456789", photo: [], botInfo: nil, restrictionInfo: nil, flags: [])
transaction.updatePeersInternal([accountPeer], update: { _, updated in
return updated
})
let baseDate: Int32 = Int32(Date().timeIntervalSince1970) - 10000
for item in chatList {
let peer = item.message.peer.peer(account.postbox)
let peer = item.message.peer.peer(context.account.postbox)
transaction.updatePeersInternal([peer], update: { _, updated in
return updated
})
if let additionalPeer = item.message.peer.additionalPeer(account.postbox) {
if let additionalPeer = item.message.peer.additionalPeer(context.account.postbox) {
transaction.updatePeersInternal([additionalPeer], update: { _, updated in
return updated
})
}
transaction.updatePeerChatListInclusion(peer.id, inclusion: .ifHasMessages)
let _ = transaction.addMessages([item.message.storeMessage(account.peerId, baseDate)], location: .UpperHistoryBlock)
let _ = transaction.addMessages([item.message.storeMessage(context.account.peerId, baseDate)], location: .UpperHistoryBlock)
transaction.resetIncomingReadStates([peer.id: [Namespaces.Message.Cloud: .idBased(maxIncomingReadId: Int32.max - 1, maxOutgoingReadId: Int32.max - 1, maxKnownId: Int32.max - 1, count: item.unreadCount, markedUnread: false)]])
if item.isMuted {
transaction.updateCurrentPeerNotificationSettings([peer.id: TelegramPeerNotificationSettings.defaultSettings.withUpdatedMuteState(.muted(until: Int32.max - 1))])
@@ -145,7 +145,7 @@ func snapshotChatList(application: UIApplication, mainWindow: UIWindow, window:
transaction.setPinnedItemIds(chatList.filter{ $0.isPinned }.map{ .peer($0.message.peer.peerId) })
}).start()
let rootController = TelegramRootController(account: account)
let rootController = TelegramRootController(context: context)
rootController.addRootControllers(showCallsTab: true)
window.viewController = rootController
rootController.rootTabController!.selectedIndex = 0

View File

@@ -12,7 +12,7 @@ enum SnapshotEnvironmentTheme {
case day
}
func snapshotEnvironment(application: UIApplication, mainWindow: UIWindow, statusBarHost: StatusBarHost, theme: SnapshotEnvironmentTheme) -> (Account, AccountManager) {
func snapshotEnvironment(application: UIApplication, mainWindow: UIWindow, statusBarHost: StatusBarHost, theme: SnapshotEnvironmentTheme) -> (AccountContext, AccountManager) {
var randomId: Int64 = 0
arc4random_buf(&randomId, 8)
let path = NSTemporaryDirectory() + "\(randomId)"
@@ -106,9 +106,9 @@ func snapshotEnvironment(application: UIApplication, mainWindow: UIWindow, statu
semaphore1.wait()
precondition(dataAndSettings != nil)
result!.applicationContext = TelegramApplicationContext(applicationBindings: applicationBindings, accountManager: accountManagerValue!, account: result, initialPresentationDataAndSettings: dataAndSettings!, postbox: result!.postbox)
let context = AccountContext(account: result!, applicationBindings: applicationBindings, accountManager: accountManagerValue!, initialPresentationDataAndSettings: dataAndSettings!, postbox: result!.postbox)
return (result!, accountManagerValue!)
return (context, accountManagerValue!)
}
#endif

View File

@@ -41,15 +41,15 @@ private let messages: [SnapshotMessage] = [
]
func snapshotSecretChat(application: UIApplication, mainWindow: UIWindow, window: Window1, statusBarHost: StatusBarHost) {
let (account, _) = snapshotEnvironment(application: application, mainWindow: mainWindow, statusBarHost: statusBarHost, theme: .night)
account.network.mockConnectionStatus = .online(proxyAddress: nil)
let (context, _) = snapshotEnvironment(application: application, mainWindow: mainWindow, statusBarHost: statusBarHost, theme: .night)
context.account.network.mockConnectionStatus = .online(proxyAddress: nil)
let accountPeer = TelegramUser(id: account.peerId, accessHash: nil, firstName: "Alena", lastName: "Shy", username: "alenashy", phone: "44321456789", photo: [], botInfo: nil, restrictionInfo: nil, flags: [])
let userPeer = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 456), accessHash: nil, firstName: "Eileen", lastName: "Lockhard", username: nil, phone: "44321456789", photo: snapshotAvatar(account.postbox, 6), botInfo: nil, restrictionInfo: nil, flags: [])
let accountPeer = TelegramUser(id: context.account.peerId, accessHash: nil, firstName: "Alena", lastName: "Shy", username: "alenashy", phone: "44321456789", photo: [], botInfo: nil, restrictionInfo: nil, flags: [])
let userPeer = TelegramUser(id: PeerId(namespace: Namespaces.Peer.CloudUser, id: 456), accessHash: nil, firstName: "Eileen", lastName: "Lockhard", username: nil, phone: "44321456789", photo: snapshotAvatar(context.account.postbox, 6), botInfo: nil, restrictionInfo: nil, flags: [])
let secretPeer = TelegramSecretChat(id: PeerId(namespace: Namespaces.Peer.SecretChat, id: 456), creationDate: 123, regularPeerId: userPeer.id, accessHash: 123, role: .creator, embeddedState: .active, messageAutoremoveTimeout: nil)
let _ = (account.postbox.transaction { transaction -> Void in
if let hole = account.postbox.seedConfiguration.initializeChatListWithHole.topLevel {
let _ = (context.account.postbox.transaction { transaction -> Void in
if let hole = context.account.postbox.seedConfiguration.initializeChatListWithHole.topLevel {
transaction.replaceChatListHole(groupId: nil, index: hole.index, hole: nil)
}
@@ -61,15 +61,15 @@ func snapshotSecretChat(application: UIApplication, mainWindow: UIWindow, window
var date: Int32 = Int32(Date().timeIntervalSince1970) - 1000
for message in messages {
let _ = transaction.addMessages([message.storeMessage(account.postbox, peerId: secretPeer.id, userPeerId: userPeer.id, accountPeerId: account.peerId, date)], location: .UpperHistoryBlock)
let _ = transaction.addMessages([message.storeMessage(context.account.postbox, peerId: secretPeer.id, userPeerId: userPeer.id, accountPeerId: context.account.peerId, date)], location: .UpperHistoryBlock)
date += 10
}
}).start()
let rootController = TelegramRootController(account: account)
let rootController = TelegramRootController(context: context)
rootController.addRootControllers(showCallsTab: true)
window.viewController = rootController
navigateToChatController(navigationController: rootController, account: account, chatLocation: .peer(secretPeer.id), animated: false)
navigateToChatController(navigationController: rootController, context: context, chatLocation: .peer(secretPeer.id), animated: false)
}
#endif

View File

@@ -8,25 +8,25 @@ import Display
import TelegramUI
func snapshotSettings(application: UIApplication, mainWindow: UIWindow, window: Window1, statusBarHost: StatusBarHost) {
let (account, accountManager) = snapshotEnvironment(application: application, mainWindow: mainWindow, statusBarHost: statusBarHost, theme: .night)
account.network.mockConnectionStatus = .online(proxyAddress: nil)
let (context, accountManager) = snapshotEnvironment(application: application, mainWindow: mainWindow, statusBarHost: statusBarHost, theme: .night)
context.account.network.mockConnectionStatus = .online(proxyAddress: nil)
let _ = (account.postbox.transaction { transaction -> Void in
if let hole = account.postbox.seedConfiguration.initializeChatListWithHole.topLevel {
let _ = (context.account.postbox.transaction { transaction -> Void in
if let hole = context.account.postbox.seedConfiguration.initializeChatListWithHole.topLevel {
transaction.replaceChatListHole(groupId: nil, index: hole.index, hole: nil)
}
let accountPeer = TelegramUser(id: account.peerId, accessHash: nil, firstName: "Alena", lastName: "Shy", username: "alenashy", phone: "44321456789", photo: snapshotAvatar(account.postbox, 1), botInfo: nil, restrictionInfo: nil, flags: [])
let accountPeer = TelegramUser(id: context.account.peerId, accessHash: nil, firstName: "Alena", lastName: "Shy", username: "alenashy", phone: "44321456789", photo: snapshotAvatar(context.account.postbox, 1), botInfo: nil, restrictionInfo: nil, flags: [])
transaction.updatePeersInternal([accountPeer], update: { _, updated in
return updated
})
}).start()
let rootController = TelegramRootController(account: account)
let rootController = TelegramRootController(context: context)
rootController.addRootControllers(showCallsTab: true)
window.viewController = rootController
rootController.rootTabController!.selectedIndex = 3
rootController.pushViewController(settingsController(account: account, accountManager: accountManager))
rootController.pushViewController(settingsController(context: context, accountManager: accountManager))
}
#endif

View File

@@ -11,7 +11,7 @@ final class WatchCommunicationManager {
private let contextDisposable = MetaDisposable()
private let presetsDisposable = MetaDisposable()
let account = Promise<Account?>(nil)
let accountContext = Promise<AccountContext?>(nil)
private let presets = Promise<WatchPresetSettings?>(nil)
private let navigateToMessagePipe = ValuePipe<MessageId>()
@@ -58,20 +58,20 @@ final class WatchCommunicationManager {
return
}
if let appContext = appContext, case let .authorized(context) = appContext {
strongSelf.account.set(.single(context.account))
strongSelf.server.setAuthorized(true, userId: context.account.peerId.id)
strongSelf.accountContext.set(.single(context.context))
strongSelf.server.setAuthorized(true, userId: context.context.account.peerId.id)
strongSelf.server.setMicAccessAllowed(false)
strongSelf.server.pushContext()
strongSelf.server.setMicAccessAllowed(true)
strongSelf.server.pushContext()
let watchPresetSettingsKey = ApplicationSpecificPreferencesKeys.watchPresetSettings
strongSelf.presets.set(context.account.postbox.preferencesView(keys: [watchPresetSettingsKey])
strongSelf.presets.set(context.context.account.postbox.preferencesView(keys: [watchPresetSettingsKey])
|> map({ preferences -> WatchPresetSettings in
return (preferences.values[watchPresetSettingsKey] as? WatchPresetSettings) ?? WatchPresetSettings.defaultSettings
}))
} else {
strongSelf.account.set(.single(nil))
strongSelf.accountContext.set(.single(nil))
strongSelf.server.setAuthorized(false, userId: 0)
strongSelf.server.pushContext()
@@ -83,7 +83,7 @@ final class WatchCommunicationManager {
guard let strongSelf = self, let presets = presets, let appContext = appContext, case let .authorized(context) = appContext, appInstalled, let tempPath = strongSelf.watchTemporaryStorePath else {
return
}
let presentationData = context.account.telegramApplicationContext.currentPresentationData.with { $0 }
let presentationData = context.context.currentPresentationData.with { $0 }
let defaultSuggestions: [String : String] = [
"OK": presentationData.strings.Watch_Suggestion_OK,
"Thanks": presentationData.strings.Watch_Suggestion_Thanks,

View File

@@ -33,13 +33,13 @@ final class WatchChatListHandler: WatchRequestHandler {
if let args = subscription as? TGBridgeChatListSubscription {
let limit = Int(args.limit)
return SSignal { subscriber in
let signal = manager.account.get()
let signal = manager.accountContext.get()
|> take(1)
|> mapToSignal({ account -> Signal<(ChatListView, PresentationData), NoError> in
if let account = account {
return account.viewTracker.tailChatListView(groupId: nil, count: limit)
|> mapToSignal({ context -> Signal<(ChatListView, PresentationData), NoError> in
if let context = context {
return context.account.viewTracker.tailChatListView(groupId: nil, count: limit)
|> map { chatListView, _ -> (ChatListView, PresentationData) in
return (chatListView, account.telegramApplicationContext.currentPresentationData.with { $0 })
return (chatListView, context.currentPresentationData.with { $0 })
}
} else {
return .complete()
@@ -81,13 +81,13 @@ final class WatchChatMessagesHandler: WatchRequestHandler {
if let args = subscription as? TGBridgeChatMessageListSubscription, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) {
return SSignal { subscriber in
let limit = Int(args.rangeMessageCount)
let signal = manager.account.get()
let signal = manager.accountContext.get()
|> take(1)
|> mapToSignal({ account -> Signal<(MessageHistoryView, Bool, PresentationData), NoError> in
if let account = account {
return account.viewTracker.aroundMessageHistoryViewForLocation(.peer(peerId), index: .upperBound, anchorIndex: .upperBound, count: limit, fixedCombinedReadStates: nil)
|> mapToSignal({ context -> Signal<(MessageHistoryView, Bool, PresentationData), NoError> in
if let context = context {
return context.account.viewTracker.aroundMessageHistoryViewForLocation(.peer(peerId), index: .upperBound, anchorIndex: .upperBound, count: limit, fixedCombinedReadStates: nil)
|> map { messageHistoryView, _, _ -> (MessageHistoryView, Bool, PresentationData) in
return (messageHistoryView, peerId == account.peerId, account.telegramApplicationContext.currentPresentationData.with { $0 })
return (messageHistoryView, peerId == context.account.peerId, context.currentPresentationData.with { $0 })
}
} else {
return .complete()
@@ -111,12 +111,12 @@ final class WatchChatMessagesHandler: WatchRequestHandler {
}
} else if let args = subscription as? TGBridgeReadChatMessageListSubscription, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) {
return SSignal { subscriber in
let signal = manager.account.get()
let signal = manager.accountContext.get()
|> take(1)
|> mapToSignal({ account -> Signal<Void, NoError> in
if let account = account {
|> mapToSignal({ context -> Signal<Void, NoError> in
if let context = context {
let messageId = MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: args.messageId)
return applyMaxReadIndexInteractively(postbox: account.postbox, stateManager: account.stateManager, index: MessageIndex(id: messageId, timestamp: 0))
return applyMaxReadIndexInteractively(postbox: context.account.postbox, stateManager: context.account.stateManager, index: MessageIndex(id: messageId, timestamp: 0))
} else {
return .complete()
}
@@ -133,14 +133,14 @@ final class WatchChatMessagesHandler: WatchRequestHandler {
}
} else if let args = subscription as? TGBridgeChatMessageSubscription, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) {
return SSignal { subscriber in
let signal = manager.account.get()
let signal = manager.accountContext.get()
|> take(1)
|> mapToSignal({ account -> Signal<(Message, PresentationData)?, NoError> in
if let account = account {
let messageSignal = downloadMessage(postbox: account.postbox, network: account.network, messageId: MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: args.messageId))
|> mapToSignal({ context -> Signal<(Message, PresentationData)?, NoError> in
if let context = context {
let messageSignal = downloadMessage(postbox: context.account.postbox, network: context.account.network, messageId: MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: args.messageId))
|> map { message -> (Message, PresentationData)? in
if let message = message {
return (message, account.telegramApplicationContext.currentPresentationData.with { $0 })
return (message, context.currentPresentationData.with { $0 })
} else {
return nil
}
@@ -182,10 +182,10 @@ final class WatchSendMessageHandler: WatchRequestHandler {
static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal {
return SSignal { subscriber in
let signal = manager.account.get()
let signal = manager.accountContext.get()
|> take(1)
|> mapToSignal({ account -> Signal<Bool, NoError> in
if let account = account {
|> mapToSignal({ context -> Signal<Bool, NoError> in
if let context = context {
var messageSignal: Signal<(EnqueueMessage?, PeerId?), NoError>?
if let args = subscription as? TGBridgeSendTextMessageSubscription {
let peerId = makePeerIdFromBridgeIdentifier(args.peerId)
@@ -200,7 +200,7 @@ final class WatchSendMessageHandler: WatchRequestHandler {
messageSignal = .single((.message(text: "", attributes: [], mediaReference: .standalone(media: map), replyToMessageId: nil, localGroupingKey: nil), peerId))
} else if let args = subscription as? TGBridgeSendStickerMessageSubscription {
let peerId = makePeerIdFromBridgeIdentifier(args.peerId)
messageSignal = mediaForSticker(documentId: args.document.documentId, account: account)
messageSignal = mediaForSticker(documentId: args.document.documentId, account: context.account)
|> map({ media -> (EnqueueMessage?, PeerId?) in
if let media = media {
return (.message(text: "", attributes: [], mediaReference: .standalone(media: media), replyToMessageId: nil, localGroupingKey: nil), peerId)
@@ -218,7 +218,7 @@ final class WatchSendMessageHandler: WatchRequestHandler {
if let messageSignal = messageSignal {
return messageSignal |> mapToSignal({ message, peerId -> Signal<Bool, NoError> in
if let message = message, let peerId = peerId {
return enqueueMessages(account: account, peerId: peerId, messages: [message]) |> mapToSignal({ _ in
return enqueueMessages(account: context.account, peerId: peerId, messages: [message]) |> mapToSignal({ _ in
return .single(true)
})
} else {
@@ -255,11 +255,11 @@ final class WatchPeerInfoHandler: WatchRequestHandler {
static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal {
if let args = subscription as? TGBridgeUserInfoSubscription {
return SSignal { subscriber in
let signal = manager.account.get()
let signal = manager.accountContext.get()
|> take(1)
|> mapToSignal({ account -> Signal<PeerView, NoError> in
if let account = account, let userId = args.userIds.first as? Int64, let peerId = makePeerIdFromBridgeIdentifier(userId) {
return account.viewTracker.peerView(peerId)
|> mapToSignal({ context -> Signal<PeerView, NoError> in
if let context = context, let userId = args.userIds.first as? Int64, let peerId = makePeerIdFromBridgeIdentifier(userId) {
return context.account.viewTracker.peerView(peerId)
} else {
return .complete()
}
@@ -279,7 +279,7 @@ final class WatchPeerInfoHandler: WatchRequestHandler {
} else if let _ = subscription as? TGBridgeUserBotInfoSubscription {
return SSignal.complete()
// return SSignal { subscriber in
// let signal = manager.account.get()
// let signal = manager.accountContext.get()
// |> take(1)
// |> mapToSignal({ account -> Signal<PeerView, NoError> in
// if let account = account, let userId = args.userIds.first as? Int64, let peerId = makePeerIdFromBridgeIdentifier(userId) {
@@ -302,9 +302,9 @@ final class WatchPeerInfoHandler: WatchRequestHandler {
// }
} else if let args = subscription as? TGBridgeConversationSubscription {
return SSignal { subscriber in
let signal = manager.account.get() |> take(1) |> mapToSignal({ account -> Signal<PeerView, NoError> in
if let account = account, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) {
return account.viewTracker.peerView(peerId)
let signal = manager.accountContext.get() |> take(1) |> mapToSignal({ context -> Signal<PeerView, NoError> in
if let context = context, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) {
return context.account.viewTracker.peerView(peerId)
} else {
return .complete()
}
@@ -398,11 +398,11 @@ final class WatchMediaHandler: WatchRequestHandler {
}
return SSignal { subscriber in
let signal = manager.account.get()
let signal = manager.accountContext.get()
|> take(1)
|> mapToSignal({ account -> Signal<UIImage?, NoError> in
if let account = account {
return account.postbox.transaction { transaction -> Peer? in
|> mapToSignal({ context -> Signal<UIImage?, NoError> in
if let context = context {
return context.account.postbox.transaction { transaction -> Peer? in
guard let peer = transaction.getPeer(peerId) else {
return nil
}
@@ -413,9 +413,9 @@ final class WatchMediaHandler: WatchRequestHandler {
}
} |> mapToSignal({ peer -> Signal<UIImage?, NoError> in
if let peer = peer, let representation = peer.smallProfileImage {
let imageData = peerAvatarImageData(account: account, peer: peer, authorOfMessage: nil, representation: representation, synchronousLoad: false)
let imageData = peerAvatarImageData(account: context.account, peer: peer, authorOfMessage: nil, representation: representation, synchronousLoad: false)
if let imageData = imageData {
return imageData |> deliverOn(account.graphicsThreadPool)
return imageData |> deliverOn(Queue.concurrentDefaultQueue())
|> map { data -> UIImage? in
if let data = data, let image = generateImage(targetSize, contextGenerator: { size, context -> Void in
if let imageSource = CGImageSourceCreateWithData(data as CFData, nil), let dataImage = CGImageSourceCreateImageAtIndex(imageSource, 0, nil) {
@@ -456,13 +456,13 @@ final class WatchMediaHandler: WatchRequestHandler {
} else if let args = subscription as? TGBridgeMediaStickerSubscription {
let key = "sticker_\(args.documentId)_\(Int(args.size.width))x\(Int(args.size.height))_\(args.notification ? 1 : 0)"
return SSignal { subscriber in
let signal = manager.account.get()
let signal = manager.accountContext.get()
|> take(1)
|> mapToSignal({ account -> Signal<UIImage?, NoError> in
if let account = account {
|> mapToSignal({ context -> Signal<UIImage?, NoError> in
if let context = context {
var mediaSignal: Signal<(TelegramMediaFile, FileMediaReference)?, NoError>? = nil
if args.stickerPackId != 0 {
mediaSignal = mediaForSticker(documentId: args.documentId, account: account)
mediaSignal = mediaForSticker(documentId: args.documentId, account: context.account)
|> map { media -> (TelegramMediaFile, FileMediaReference)? in
if let media = media {
return (media, .standalone(media: media))
@@ -471,7 +471,7 @@ final class WatchMediaHandler: WatchRequestHandler {
}
}
} else if args.stickerPeerId != 0, let peerId = makePeerIdFromBridgeIdentifier(args.stickerPeerId) {
mediaSignal = account.postbox.transaction { transaction -> Message? in
mediaSignal = context.account.postbox.transaction { transaction -> Message? in
return transaction.getMessage(MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: args.stickerMessageId))
}
|> map { message -> (TelegramMediaFile, FileMediaReference)? in
@@ -493,8 +493,8 @@ final class WatchMediaHandler: WatchRequestHandler {
if let dimensions = media.dimensions {
size = dimensions
}
self.disposable.add(freeMediaFileInteractiveFetched(account: account, fileReference: fileReference).start())
return chatMessageSticker(account: account, file: media, small: false, fetched: true, onlyFullSize: true)
self.disposable.add(freeMediaFileInteractiveFetched(account: context.account, fileReference: fileReference).start())
return chatMessageSticker(account: context.account, file: media, small: false, fetched: true, onlyFullSize: true)
}
return .complete()
}
@@ -523,12 +523,12 @@ final class WatchMediaHandler: WatchRequestHandler {
} else if let args = subscription as? TGBridgeMediaThumbnailSubscription {
let key = "\(args.peerId)_\(args.messageId)"
return SSignal { subscriber in
let signal = manager.account.get()
let signal = manager.accountContext.get()
|> take(1)
|> mapToSignal({ account -> Signal<UIImage?, NoError> in
if let account = account, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) {
|> mapToSignal({ context -> Signal<UIImage?, NoError> in
if let context = context, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) {
var roundVideo = false
return account.postbox.transaction { transaction -> Message? in
return context.account.postbox.transaction { transaction -> Message? in
return transaction.getMessage(MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: args.messageId))
}
|> mapToSignal { message -> Signal<(TransformImageArguments) -> DrawingContext?, NoError> in
@@ -539,14 +539,14 @@ final class WatchMediaHandler: WatchRequestHandler {
var imageDimensions: CGSize?
for media in message.media {
if let image = media as? TelegramMediaImage, let resource = largestImageRepresentation(image.representations)?.resource {
self.disposable.add(messageMediaImageInteractiveFetched(account: account, message: message, image: image, resource: resource, storeToDownloadsPeerType: nil).start())
self.disposable.add(messageMediaImageInteractiveFetched(context: context, message: message, image: image, resource: resource, storeToDownloadsPeerType: nil).start())
candidateMediaReference = .message(message: MessageReference(message), media: media)
break
} else if let _ = media as? TelegramMediaFile {
candidateMediaReference = .message(message: MessageReference(message), media: media)
break
} else if let webPage = media as? TelegramMediaWebpage, case let .Loaded(content) = webPage.content, let image = content.image, let resource = largestImageRepresentation(image.representations)?.resource {
self.disposable.add(messageMediaImageInteractiveFetched(account: account, message: message, image: image, resource: resource, storeToDownloadsPeerType: nil).start())
self.disposable.add(messageMediaImageInteractiveFetched(context: context, message: message, image: image, resource: resource, storeToDownloadsPeerType: nil).start())
candidateMediaReference = .webPage(webPage: WebpageReference(webPage), media: image)
break
}
@@ -564,13 +564,13 @@ final class WatchMediaHandler: WatchRequestHandler {
}
if let updatedMediaReference = updatedMediaReference, imageDimensions != nil {
if let imageReference = updatedMediaReference.concrete(TelegramMediaImage.self) {
imageSignal = chatMessagePhotoThumbnail(account: account, photoReference: imageReference, onlyFullSize: true)
imageSignal = chatMessagePhotoThumbnail(account: context.account, photoReference: imageReference, onlyFullSize: true)
} else if let fileReference = updatedMediaReference.concrete(TelegramMediaFile.self) {
if fileReference.media.isVideo {
imageSignal = chatMessageVideoThumbnail(account: account, fileReference: fileReference)
imageSignal = chatMessageVideoThumbnail(account: context.account, fileReference: fileReference)
roundVideo = fileReference.media.isInstantVideo
} else if let iconImageRepresentation = smallestImageRepresentation(fileReference.media.previewRepresentations) {
imageSignal = chatWebpageSnippetFile(account: account, fileReference: fileReference, representation: iconImageRepresentation)
imageSignal = chatWebpageSnippetFile(account: context.account, fileReference: fileReference, representation: iconImageRepresentation)
}
}
}
@@ -618,11 +618,11 @@ final class WatchStickersHandler: WatchRequestHandler {
static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal {
if let args = subscription as? TGBridgeRecentStickersSubscription {
return SSignal { subscriber in
let signal = manager.account.get()
let signal = manager.accountContext.get()
|> take(1)
|> mapToSignal({ account -> Signal<ItemCollectionsView, NoError> in
if let account = account {
return account.postbox.itemCollectionsView(orderedItemListCollectionIds: [Namespaces.OrderedItemList.CloudSavedStickers, Namespaces.OrderedItemList.CloudRecentStickers], namespaces: [Namespaces.ItemCollection.CloudStickerPacks], aroundIndex: nil, count: 50) |> take(1)
|> mapToSignal({ context -> Signal<ItemCollectionsView, NoError> in
if let context = context {
return context.account.postbox.itemCollectionsView(orderedItemListCollectionIds: [Namespaces.OrderedItemList.CloudSavedStickers, Namespaces.OrderedItemList.CloudRecentStickers], namespaces: [Namespaces.ItemCollection.CloudStickerPacks], aroundIndex: nil, count: 50) |> take(1)
} else {
return .complete()
}
@@ -674,19 +674,19 @@ final class WatchAudioHandler: WatchRequestHandler {
if let args = subscription as? TGBridgeAudioSubscription {
let key = "audio_\(args.peerId)_\(args.messageId)"
return SSignal { subscriber in
let signal = manager.account.get()
let signal = manager.accountContext.get()
|> take(1)
|> mapToSignal({ account -> Signal<String, NoError> in
if let account = account, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) {
return account.postbox.transaction { transaction -> Message? in
|> mapToSignal({ context -> Signal<String, NoError> in
if let context = context, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) {
return context.account.postbox.transaction { transaction -> Message? in
return transaction.getMessage(MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: args.messageId))
}
|> mapToSignal { message -> Signal<String, NoError> in
if let message = message {
for media in message.media {
if let file = media as? TelegramMediaFile {
self.disposable.add(messageMediaFileInteractiveFetched(account: account, message: message, file: file, userInitiated: true).start())
return account.postbox.mediaBox.resourceData(file.resource)
self.disposable.add(messageMediaFileInteractiveFetched(context: context, message: message, file: file, userInitiated: true).start())
return context.account.postbox.mediaBox.resourceData(file.resource)
|> mapToSignal({ data -> Signal<String, NoError> in
if let tempPath = manager.watchTemporaryStorePath, data.complete {
let outputPath = tempPath + "/\(key).m4a"
@@ -729,20 +729,19 @@ final class WatchAudioHandler: WatchRequestHandler {
let replyToMid = metadata[TGBridgeIncomingFileReplyToMidKey] as? Int32
if let randomId = randomId, let id = peerId, let peerId = makePeerIdFromBridgeIdentifier(id) {
return combineLatest(manager.account.get() |> take(1), legacyEncodeOpusAudio(path: path))
|> map({ account, pathAndDuration -> Void in
return combineLatest(manager.accountContext.get() |> take(1), legacyEncodeOpusAudio(path: path))
|> map({ context, pathAndDuration -> Void in
let (path, duration) = pathAndDuration
if let account = account, let path = path, let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
if let context = context, let path = path, let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let resource = LocalFileMediaResource(fileId: randomId)
account.postbox.mediaBox.storeResourceData(resource.id, data: data)
context.account.postbox.mediaBox.storeResourceData(resource.id, data: data)
var replyMessageId: MessageId? = nil
if let replyToMid = replyToMid, replyToMid != 0 {
replyMessageId = MessageId(peerId: peerId, namespace: Namespaces.Message.Cloud, id: replyToMid)
}
let _ = enqueueMessages(account: account, peerId: peerId, messages: [.message(text: "", attributes: [], mediaReference: .standalone(media: TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: randomId), partialReference: nil, resource: resource, previewRepresentations: [], immediateThumbnailData: nil, mimeType: "audio/ogg", size: data.count, attributes: [.Audio(isVoice: true, duration: Int(duration), title: nil, performer: nil, waveform: nil)])), replyToMessageId: replyMessageId, localGroupingKey: nil)]).start()
let _ = enqueueMessages(account: context.account, peerId: peerId, messages: [.message(text: "", attributes: [], mediaReference: .standalone(media: TelegramMediaFile(fileId: MediaId(namespace: Namespaces.Media.LocalFile, id: randomId), partialReference: nil, resource: resource, previewRepresentations: [], immediateThumbnailData: nil, mimeType: "audio/ogg", size: data.count, attributes: [.Audio(isVoice: true, duration: Int(duration), title: nil, performer: nil, waveform: nil)])), replyToMessageId: replyMessageId, localGroupingKey: nil)]).start()
}
})
} else {
@@ -759,23 +758,23 @@ final class WatchLocationHandler: WatchRequestHandler {
static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal {
if let args = subscription as? TGBridgeNearbyVenuesSubscription {
return SSignal { subscriber in
let signal = manager.account.get()
let signal = manager.accountContext.get()
|> take(1)
|> mapToSignal({ account -> Signal<[ChatContextResultMessage], NoError> in
if let account = account {
return resolvePeerByName(account: account, name: "foursquare")
|> take(1)
|> mapToSignal { peerId -> Signal<ChatContextResultCollection?, NoError> in
guard let peerId = peerId else {
return .single(nil)
}
return requestChatContextResults(account: account, botId: peerId, peerId: account.peerId, query: "", location: .single((args.coordinate.latitude, args.coordinate.longitude)), offset: "")
|> mapToSignal({ context -> Signal<[ChatContextResultMessage], NoError> in
if let context = context {
return resolvePeerByName(account: context.account, name: "foursquare")
|> take(1)
|> mapToSignal { peerId -> Signal<ChatContextResultCollection?, NoError> in
guard let peerId = peerId else {
return .single(nil)
}
|> mapToSignal { contextResult -> Signal<[ChatContextResultMessage], NoError> in
guard let contextResult = contextResult else {
return .single([])
}
return .single(contextResult.results.map { $0.message })
return requestChatContextResults(account: context.account, botId: peerId, peerId: context.account.peerId, query: "", location: .single((args.coordinate.latitude, args.coordinate.longitude)), offset: "")
}
|> mapToSignal { contextResult -> Signal<[ChatContextResultMessage], NoError> in
guard let contextResult = contextResult else {
return .single([])
}
return .single(contextResult.results.map { $0.message })
}
} else {
return .complete()
@@ -813,11 +812,11 @@ final class WatchPeerSettingsHandler: WatchRequestHandler {
static func handle(subscription: TGBridgeSubscription, manager: WatchCommunicationManager) -> SSignal {
if let args = subscription as? TGBridgePeerSettingsSubscription {
return SSignal { subscriber in
let signal = manager.account.get()
let signal = manager.accountContext.get()
|> take(1)
|> mapToSignal({ account -> Signal<PeerView, NoError> in
if let account = account, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) {
return account.viewTracker.peerView(peerId)
|> mapToSignal({ context -> Signal<PeerView, NoError> in
if let context = context, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) {
return context.account.viewTracker.peerView(peerId)
} else {
return .complete()
}
@@ -842,16 +841,16 @@ final class WatchPeerSettingsHandler: WatchRequestHandler {
}
} else {
return SSignal { subscriber in
let signal = manager.account.get()
let signal = manager.accountContext.get()
|> take(1)
|> mapToSignal({ account -> Signal<Bool, NoError> in
if let account = account {
|> mapToSignal({ context -> Signal<Bool, NoError> in
if let context = context {
var signal: Signal<Void, NoError>?
if let args = subscription as? TGBridgePeerUpdateNotificationSettingsSubscription, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) {
signal = togglePeerMuted(account: account, peerId: peerId)
signal = togglePeerMuted(account: context.account, peerId: peerId)
} else if let args = subscription as? TGBridgePeerUpdateBlockStatusSubscription, let peerId = makePeerIdFromBridgeIdentifier(args.peerId) {
signal = requestUpdatePeerIsBlocked(account: account, peerId: peerId, isBlocked: args.blocked)
signal = requestUpdatePeerIsBlocked(account: context.account, peerId: peerId, isBlocked: args.blocked)
}
if let signal = signal {