Refactoring

This commit is contained in:
Ali 2021-03-24 02:56:24 +04:00
parent 50fe822e85
commit 2f9189d220
39 changed files with 16 additions and 468 deletions

View File

@ -157,7 +157,7 @@ public func logoutOptionsController(context: AccountContext, navigationControlle
dismissImpl?()
}, contactSupport: { [weak navigationController] in
let supportPeer = Promise<PeerId?>()
supportPeer.set(supportPeerId(account: context.account))
supportPeer.set(context.engine.peerNames.supportPeerId())
let presentationData = context.sharedContext.currentPresentationData.with { $0 }
var faqUrl = presentationData.strings.Settings_FAQ_URL

View File

@ -883,7 +883,7 @@ func settingsSearchableItems(context: AccountContext, notificationExceptionsList
}
let support = SettingsSearchableItem(id: .support(0), title: strings.Settings_Support, alternate: synonyms(strings.SettingsSearch_Synonyms_Support), icon: .support, breadcrumbs: [], present: { context, _, present in
let _ = (supportPeerId(account: context.account)
let _ = (context.engine.peerNames.supportPeerId()
|> deliverOnMainQueue).start(next: { peerId in
if let peerId = peerId {
present(.push, context.sharedContext.makeChatController(context: context, chatLocation: .peer(peerId), subject: nil, botStart: nil, mode: .standard(previewing: false)))

View File

@ -1,292 +0,0 @@
import Foundation
import Postbox
import SwiftSignalKit
import TelegramApi
import MtProtoKit
import SyncCore
private struct LocalChatListEntryRange {
var entries: [ChatListNamespaceEntry]
var upperBound: ChatListIndex?
var lowerBound: ChatListIndex
var count: Int32
var hash: UInt32
var apiHash: Int32 {
return Int32(bitPattern: self.hash & UInt32(0x7FFFFFFF))
}
}
private func combineHash(_ value: Int32, into hash: inout UInt32) {
let low = UInt32(bitPattern: value)
hash = (hash &* 20261) &+ low
}
private func combineChatListNamespaceEntryHash(index: ChatListIndex, readState: PeerReadState?, topMessageAttributes: [MessageAttribute], tagSummary: MessageHistoryTagNamespaceSummary?, interfaceState: PeerChatInterfaceState?, into hash: inout UInt32) {
/*
dialog.pinned ? 1 : 0,
dialog.unread_mark ? 1 : 0,
dialog.peer.channel_id || dialog.peer.chat_id || dialog.peer.user_id,
dialog.top_message.id,
top_message.edit_date || top_message.date,
dialog.read_inbox_max_id,
dialog.read_outbox_max_id,
dialog.unread_count,
dialog.unread_mentions_count,
draft.draft.date || 0
*/
combineHash(index.pinningIndex != nil ? 1 : 0, into: &hash)
if let readState = readState, readState.markedUnread {
combineHash(1, into: &hash)
} else {
combineHash(0, into: &hash)
}
combineHash(index.messageIndex.id.peerId.id, into: &hash)
combineHash(index.messageIndex.id.id, into: &hash)
var timestamp = index.messageIndex.timestamp
for attribute in topMessageAttributes {
if let attribute = attribute as? EditedMessageAttribute {
timestamp = max(timestamp, attribute.date)
}
}
combineHash(timestamp, into: &hash)
if let readState = readState, case let .idBased(maxIncomingReadId, maxOutgoingReadId, _, count, _) = readState {
combineHash(maxIncomingReadId, into: &hash)
combineHash(maxOutgoingReadId, into: &hash)
combineHash(count, into: &hash)
} else {
combineHash(0, into: &hash)
combineHash(0, into: &hash)
combineHash(0, into: &hash)
}
if let tagSummary = tagSummary {
combineHash(tagSummary.count, into: &hash)
} else {
combineHash(0, into: &hash)
}
if let embeddedState = interfaceState?.chatListEmbeddedState {
combineHash(embeddedState.timestamp, into: &hash)
} else {
combineHash(0, into: &hash)
}
}
private func localChatListEntryRanges(_ entries: [ChatListNamespaceEntry], limit: Int) -> [LocalChatListEntryRange] {
var result: [LocalChatListEntryRange] = []
var currentRange: LocalChatListEntryRange?
for i in 0 ..< entries.count {
switch entries[i] {
case let .peer(index, readState, topMessageAttributes, tagSummary, interfaceState):
var updatedRange: LocalChatListEntryRange
if let current = currentRange {
updatedRange = current
} else {
updatedRange = LocalChatListEntryRange(entries: [], upperBound: result.last?.lowerBound, lowerBound: index, count: 0, hash: 0)
}
updatedRange.entries.append(entries[i])
updatedRange.lowerBound = index
updatedRange.count += 1
combineChatListNamespaceEntryHash(index: index, readState: readState, topMessageAttributes: topMessageAttributes, tagSummary: tagSummary, interfaceState: interfaceState, into: &updatedRange.hash)
if Int(updatedRange.count) >= limit {
result.append(updatedRange)
currentRange = nil
} else {
currentRange = updatedRange
}
case .hole:
if let currentRangeValue = currentRange {
result.append(currentRangeValue)
currentRange = nil
}
}
}
if let currentRangeValue = currentRange {
result.append(currentRangeValue)
currentRange = nil
}
return result
}
private struct ResolvedChatListResetRange {
let head: Bool
let local: LocalChatListEntryRange
let remote: FetchedChatList
}
/*func accountStateReset(postbox: Postbox, network: Network, accountPeerId: PeerId) -> Signal<Void, NoError> {
let pinnedChats: Signal<Api.messages.PeerDialogs, NoError> = network.request(Api.functions.messages.getPinnedDialogs(folderId: 0))
|> retryRequest
let state: Signal<Api.updates.State, NoError> = network.request(Api.functions.updates.getState())
|> retryRequest
return postbox.transaction { transaction -> [ChatListNamespaceEntry] in
return transaction.getChatListNamespaceEntries(groupId: .root, namespace: Namespaces.Message.Cloud, summaryTag: MessageTags.unseenPersonalMessage)
}
|> mapToSignal { localChatListEntries -> Signal<Void, NoError> in
let localRanges = localChatListEntryRanges(localChatListEntries, limit: 100)
var signal: Signal<ResolvedChatListResetRange?, NoError> = .complete()
for i in 0 ..< localRanges.count {
let upperBound: MessageIndex
let head = i == 0
let localRange = localRanges[i]
if let rangeUpperBound = localRange.upperBound {
upperBound = rangeUpperBound.messageIndex.predecessor()
} else {
upperBound = MessageIndex(id: MessageId(peerId: PeerId(namespace: Namespaces.Peer.Empty, id: 0), namespace: Namespaces.Message.Cloud, id: 0), timestamp: 0)
}
let rangeSignal: Signal<ResolvedChatListResetRange?, NoError> = fetchChatList(postbox: postbox, network: network, location: .general, upperBound: upperBound, hash: localRange.apiHash, limit: localRange.count)
|> map { remote -> ResolvedChatListResetRange? in
if let remote = remote {
return ResolvedChatListResetRange(head: head, local: localRange, remote: remote)
} else {
return nil
}
}
signal = signal
|> then(rangeSignal)
}
let collectedResolvedRanges: Signal<[ResolvedChatListResetRange], NoError> = signal
|> map { next -> [ResolvedChatListResetRange] in
if let next = next {
return [next]
} else {
return []
}
}
|> reduceLeft(value: [], f: { list, next in
var list = list
list.append(contentsOf: next)
return list
})
return combineLatest(collectedResolvedRanges, state)
|> mapToSignal { collectedRanges, state -> Signal<Void, NoError> in
return postbox.transaction { transaction -> Void in
for range in collectedRanges {
let previousPeerIds = transaction.resetChatList(keepPeerNamespaces: [Namespaces.Peer.SecretChat], upperBound: range.local.upperBound ?? ChatListIndex.absoluteUpperBound, lowerBound: range.local.lowerBound)
#if DEBUG
for peerId in previousPeerIds {
print("pre \(peerId) [\(transaction.getPeer(peerId)?.debugDisplayTitle ?? "nil")]")
}
print("pre hash \(range.local.hash)")
print("")
var preRecalculatedHash: UInt32 = 0
for entry in range.local.entries {
switch entry {
case let .peer(index, readState, topMessageAttributes, tagSummary, interfaceState):
print("val \(index.messageIndex.id.peerId) [\(transaction.getPeer(index.messageIndex.id.peerId)?.debugDisplayTitle ?? "nil")]")
combineChatListNamespaceEntryHash(index: index, readState: readState, topMessageAttributes: topMessageAttributes, tagSummary: nil, interfaceState: nil, into: &preRecalculatedHash)
default:
break
}
}
print("pre recalculated hash \(preRecalculatedHash)")
print("")
var hash: UInt32 = 0
range.remote.storeMessages.compactMap({ message -> MessageIndex? in
if case let .Id(id) = message.id {
if range.remote.topMessageIds[id.peerId] == id {
return message.index
}
}
return nil
}).sorted(by: { lhs, rhs in
return lhs > rhs
}).forEach({ index in
var topMessageAttributes: [MessageAttribute] = []
for message in range.remote.storeMessages {
if case let .Id(id) = message.id, id == index.id {
topMessageAttributes = message.attributes
}
}
combineChatListNamespaceEntryHash(index: ChatListIndex(pinningIndex: nil, messageIndex: index), readState: range.remote.readStates[index.id.peerId]?[Namespaces.Message.Cloud], topMessageAttributes: topMessageAttributes, tagSummary: nil, interfaceState: nil, into: &hash)
print("upd \(index.id.peerId) [\(transaction.getPeer(index.id.peerId)?.debugDisplayTitle ?? "nil")]")
})
print("upd hash \(hash)")
#endif
updatePeers(transaction: transaction, peers: range.remote.peers, update: { _, updated -> Peer in
return updated
})
updatePeerPresences(transaction: transaction, accountPeerId: accountPeerId, peerPresences: range.remote.peerPresences)
transaction.updateCurrentPeerNotificationSettings(range.remote.notificationSettings)
var allPeersWithMessages = Set<PeerId>()
for message in range.remote.storeMessages {
allPeersWithMessages.insert(message.id.peerId)
}
for (_, messageId) in range.remote.topMessageIds {
if messageId.id > 1 {
var skipHole = false
if let localTopId = transaction.getTopPeerMessageIndex(peerId: messageId.peerId, namespace: messageId.namespace)?.id {
if localTopId >= messageId {
skipHole = true
}
}
if !skipHole {
//transaction.addHole(MessageId(peerId: messageId.peerId, namespace: messageId.namespace, id: messageId.id - 1))
}
}
}
let _ = transaction.addMessages(range.remote.storeMessages, location: .UpperHistoryBlock)
transaction.resetIncomingReadStates(range.remote.readStates)
for (peerId, chatState) in range.remote.chatStates {
if let chatState = chatState as? ChannelState {
if let current = transaction.getPeerChatState(peerId) as? ChannelState {
transaction.setPeerChatState(peerId, state: current.withUpdatedPts(chatState.pts))
} else {
transaction.setPeerChatState(peerId, state: chatState)
}
} else {
transaction.setPeerChatState(peerId, state: chatState)
}
}
for (peerId, summary) in range.remote.mentionTagSummaries {
transaction.replaceMessageTagSummary(peerId: peerId, tagMask: .unseenPersonalMessage, namespace: Namespaces.Message.Cloud, count: summary.count, maxId: summary.range.maxId)
}
let namespacesWithHoles: [PeerId.Namespace: [MessageId.Namespace]] = [
Namespaces.Peer.CloudUser: [Namespaces.Message.Cloud],
Namespaces.Peer.CloudGroup: [Namespaces.Message.Cloud],
Namespaces.Peer.CloudChannel: [Namespaces.Message.Cloud]
]
for peerId in previousPeerIds {
if !allPeersWithMessages.contains(peerId), let namespaces = namespacesWithHoles[peerId.namespace] {
for namespace in namespaces {
//transaction.addHole(MessageId(peerId: peerId, namespace: namespace, id: Int32.max - 1))
}
}
}
if range.head {
transaction.setPinnedItemIds(groupId: nil, itemIds: range.remote.pinnedItemIds ?? [])
}
}
if let currentState = transaction.getState() as? AuthorizedAccountState, let embeddedState = currentState.state {
switch state {
case let .state(pts, _, _, seq, _):
transaction.setState(currentState.changedState(AuthorizedAccountState.State(pts: pts, qts: embeddedState.qts, date: embeddedState.date, seq: seq)))
}
}
}
}
}
}*/

View File

@ -1,2 +0,0 @@
SWIFT_INCLUDE_PATHS = $(SRCROOT)/TelegramCore
MODULEMAP_PRIVATE_FILE = $(SRCROOT)/TelegramCore/module.private.modulemap

View File

@ -1,24 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPrincipalClass</key>
<string></string>
</dict>
</plist>

View File

@ -1,119 +0,0 @@
import Foundation
import MultipeerConnectivity
protocol ColorServiceManagerDelegate {
func connectedDevicesChanged(manager : ColorServiceManager, connectedDevices: [String])
func colorChanged(manager : ColorServiceManager, colorString: String)
}
class ColorServiceManager : NSObject {
private let ColorServiceType = "tg-p2p"
private let myPeerId = MCPeerID(displayName: UIDevice.current.name)
private let serviceAdvertiser : MCNearbyServiceAdvertiser
private let serviceBrowser : MCNearbyServiceBrowser
var delegate : ColorServiceManagerDelegate?
lazy var session : MCSession = {
let session = MCSession(peer: self.myPeerId, securityIdentity: nil, encryptionPreference: .required)
session.delegate = self
return session
}()
override init() {
self.serviceAdvertiser = MCNearbyServiceAdvertiser(peer: myPeerId, discoveryInfo: nil, serviceType: ColorServiceType)
self.serviceBrowser = MCNearbyServiceBrowser(peer: myPeerId, serviceType: ColorServiceType)
super.init()
self.serviceAdvertiser.delegate = self
self.serviceAdvertiser.startAdvertisingPeer()
self.serviceBrowser.delegate = self
self.serviceBrowser.startBrowsingForPeers()
}
func send(colorName : String) {
NSLog("%@", "sendColor: \(colorName) to \(session.connectedPeers.count) peers")
if session.connectedPeers.count > 0 {
do {
try self.session.send(colorName.data(using: .utf8)!, toPeers: session.connectedPeers, with: .reliable)
}
catch let error {
NSLog("%@", "Error for sending: \(error)")
}
}
}
deinit {
self.serviceAdvertiser.stopAdvertisingPeer()
self.serviceBrowser.stopBrowsingForPeers()
}
}
extension ColorServiceManager : MCNearbyServiceAdvertiserDelegate {
func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: Error) {
NSLog("%@", "didNotStartAdvertisingPeer: \(error)")
}
func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void) {
NSLog("%@", "didReceiveInvitationFromPeer \(peerID)")
invitationHandler(true, self.session)
}
}
extension ColorServiceManager : MCNearbyServiceBrowserDelegate {
func browser(_ browser: MCNearbyServiceBrowser, didNotStartBrowsingForPeers error: Error) {
NSLog("%@", "didNotStartBrowsingForPeers: \(error)")
}
func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) {
NSLog("%@", "foundPeer: \(peerID)")
NSLog("%@", "invitePeer: \(peerID)")
browser.invitePeer(peerID, to: self.session, withContext: nil, timeout: 10)
}
func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
NSLog("%@", "lostPeer: \(peerID)")
}
}
extension ColorServiceManager : MCSessionDelegate {
func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
NSLog("%@", "peer \(peerID) didChangeState: \(state)")
self.delegate?.connectedDevicesChanged(manager: self, connectedDevices:
session.connectedPeers.map{$0.displayName})
}
func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
NSLog("%@", "didReceiveData: \(data)")
let str = String(data: data, encoding: .utf8)!
self.delegate?.colorChanged(manager: self, colorString: str)
}
func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
NSLog("%@", "didReceiveStream")
}
func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {
NSLog("%@", "didStartReceivingResourceWithName")
}
func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {
NSLog("%@", "didFinishReceivingResourceWithName")
}
}

View File

@ -63,7 +63,7 @@ extension PeerInputActivity {
self = .uploadingInstantVideo(progress: progress)
case .speakingInGroupCallAction:
self = .speakingInGroupCall(timestamp: timestamp)
case let .sendMessageHistoryImportAction(progress):
case let .sendMessageHistoryImportAction:
return nil
}
}

View File

@ -88,7 +88,7 @@ public func stickerPacksAttachedToMedia(account: Account, media: AnyMediaReferen
|> mapToSignal { reference -> Signal<[Api.StickerSetCovered], MTRpcError> in
let inputMedia: Api.InputStickeredMedia
if let resource = reference.updatedResource as? TelegramCloudMediaResourceWithFileReference, let updatedReference = resource.fileReference {
if let imageReference = media.concrete(TelegramMediaImage.self), let reference = imageReference.media.reference, case let .cloud(imageId, accessHash, _) = reference, let representation = largestImageRepresentation(imageReference.media.representations) {
if let imageReference = media.concrete(TelegramMediaImage.self), let reference = imageReference.media.reference, case let .cloud(imageId, accessHash, _) = reference, let _ = largestImageRepresentation(imageReference.media.representations) {
inputMedia = .inputStickeredMediaPhoto(id: Api.InputPhoto.inputPhoto(id: imageId, accessHash: accessHash, fileReference: Buffer(data: updatedReference)))
} else if let fileReference = media.concrete(TelegramMediaFile.self), let resource = fileReference.media.resource as? CloudDocumentMediaResource {
inputMedia = .inputStickeredMediaDocument(id: Api.InputDocument.inputDocument(id: resource.fileId, accessHash: resource.accessHash, fileReference: Buffer(data: updatedReference)))

View File

@ -1,20 +0,0 @@
//
// TelegramCore.h
// TelegramCore
//
// Created by Peter on 8/1/16.
// Copyright © 2016 Peter. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for TelegramCore.
FOUNDATION_EXPORT double TelegramCoreVersionNumber;
//! Project version string for TelegramCore.
FOUNDATION_EXPORT const unsigned char TelegramCoreVersionString[];
#import <TelegramCore/FormatPhoneNumber.h>
#import <TelegramCore/Crypto.h>
#import <TelegramCore/NetworkLogging.h>
#import <TelegramCore/Reachability.h>

View File

@ -3,7 +3,7 @@ import SwiftSignalKit
import Postbox
import TelegramApi
public func findChannelById(postbox: Postbox, network: Network, channelId: Int32) -> Signal<Peer?, NoError> {
func _internal_findChannelById(postbox: Postbox, network: Network, channelId: Int32) -> Signal<Peer?, NoError> {
return network.request(Api.functions.channels.getChannels(id: [.inputChannel(channelId: channelId, accessHash: 0)]))
|> map(Optional.init)
|> `catch` { _ -> Signal<Api.messages.Chats?, NoError> in

View File

@ -5,7 +5,7 @@ import MtProtoKit
import SyncCore
public func supportPeerId(account:Account) -> Signal<PeerId?, NoError> {
func _internal_supportPeerId(account: Account) -> Signal<PeerId?, NoError> {
return account.network.request(Api.functions.help.getSupport())
|> map(Optional.init)
|> `catch` { _ in

View File

@ -49,5 +49,13 @@ public extension TelegramEngine {
)
}
}
public func findChannelById(channelId: Int32) -> Signal<Peer?, NoError> {
return _internal_findChannelById(postbox: self.account.postbox, network: self.account.network, channelId: channelId)
}
public func supportPeerId() -> Signal<PeerId?, NoError> {
return _internal_supportPeerId(account: self.account)
}
}
}

View File

@ -1,3 +0,0 @@
module TelegramCore.TelegramCorePrivate {
export *
}

View File

@ -5336,7 +5336,7 @@ private final class PeerInfoScreenNode: ViewControllerTracingNode, UIScrollViewD
self.controller?.push(watchSettingsController(context: self.context))
case .support:
let supportPeer = Promise<PeerId?>()
supportPeer.set(supportPeerId(account: context.account))
supportPeer.set(context.engine.peerNames.supportPeerId())
self.controller?.present(textAlertController(context: self.context, title: nil, text: self.presentationData.strings.Settings_FAQ_Intro, actions: [
TextAlertAction(type: .genericAction, title: presentationData.strings.Settings_FAQ_Button, action: { [weak self] in

View File

@ -374,7 +374,7 @@ private func resolveInternalUrl(account: Account, url: ParsedInternalUrl) -> Sig
if let peer = peer {
foundPeer = .single(peer)
} else {
foundPeer = findChannelById(postbox: account.postbox, network: account.network, channelId: messageId.peerId.id)
foundPeer = TelegramEngine(account: account).peerNames.findChannelById(channelId: messageId.peerId.id)
}
return foundPeer
|> mapToSignal { foundPeer -> Signal<ResolvedUrl?, NoError> in