Home telegram - messageHistoryHoles
Post
Cancel

telegram - messageHistoryHoles

enum MessageHistoryViewRelativeHoleDirection

1
2
case range(start: MessageId, end: MessageId)
case aroundId(MessageId)

enum FetchMessageHistoryHoleSource

1
2
case network(Network)
case download(Download)

fetchMessageHistoryHole

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
func fetchMessageHistoryHole(accountPeerId: PeerId, source: FetchMessageHistoryHoleSource, postbox: Postbox, peerId: PeerId, namespace: MessageId.Namespace, direction: MessageHistoryViewRelativeHoleDirection, space: MessageHistoryHoleSpace, limit: Int = 100) -> Signal<Never, NoError> {
    return postbox.stateView()
    |> mapToSignal { view -> Signal<AuthorizedAccountState, NoError> in
        if let state = view.state as? AuthorizedAccountState {
            return .single(state)
        } else {
            return .complete()
        }
    }
    |> take(1)
    |> mapToSignal { _ -> Signal<Never, NoError> in
        return postbox.loadedPeerWithId(peerId)
        |> take(1)
        |> mapToSignal { peer in
            if let inputPeer = forceApiInputPeer(peer) {
                print("fetchMessageHistoryHole for \(peer.debugDisplayTitle) \(direction) space \(space)")
                Logger.shared.log("fetchMessageHistoryHole", "fetch for \(peer.debugDisplayTitle) \(direction) space \(space)")
                let request: Signal<Api.messages.Messages, MTRpcError>
                var implicitelyFillHole = false
                let minMaxRange: ClosedRange<MessageId.Id>
                
                switch space {
                    case .everywhere:
                        let offsetId: Int32
                        let addOffset: Int32
                        let selectedLimit = limit
                        let maxId: Int32
                        let minId: Int32
                        
                        switch direction {
                            case let .range(start, end):
                                if start.id <= end.id {
                                    offsetId = start.id <= 1 ? 1 : (start.id - 1)
                                    addOffset = Int32(-selectedLimit)
                                    maxId = end.id
                                    minId = start.id - 1
                                    
                                    let rangeStartId = start.id
                                    let rangeEndId = min(end.id, Int32.max - 1)
                                    if rangeStartId <= rangeEndId {
                                        minMaxRange = rangeStartId ... rangeEndId
                                    } else {
                                        minMaxRange = rangeStartId ... rangeStartId
                                        assertionFailure()
                                    }
                                } else {
                                    offsetId = start.id == Int32.max ? start.id : (start.id + 1)
                                    addOffset = 0
                                    maxId = start.id == Int32.max ? start.id : (start.id + 1)
                                    minId = end.id
                                    
                                    let rangeStartId = end.id
                                    let rangeEndId = min(start.id, Int32.max - 1)
                                    if rangeStartId <= rangeEndId {
                                        minMaxRange = rangeStartId ... rangeEndId
                                    } else {
                                        minMaxRange = rangeStartId ... rangeStartId
                                        assertionFailure()
                                    }
                                }
                            case let .aroundId(id):
                                offsetId = id.id
                                addOffset = Int32(-selectedLimit / 2)
                                maxId = Int32.max
                                minId = 1
                                minMaxRange = 1 ... Int32.max - 1
                        }
                        
                  /// Api.functions.messages.getHistory
                        request = source.request(Api.functions.messages.getHistory(peer: inputPeer, offsetId: offsetId, offsetDate: 0, addOffset: addOffset, limit: Int32(selectedLimit), maxId: maxId, minId: minId, hash: 0))
                    case let .tag(tag):
                        assert(tag.containsSingleElement)
                        if tag == .unseenPersonalMessage {
                            let offsetId: Int32
                            let addOffset: Int32
                            let selectedLimit = limit
                            let maxId: Int32
                            let minId: Int32
                            
                            switch direction {
                                case let .range(start, end):
                                    if start.id <= end.id {
                                        offsetId = start.id <= 1 ? 1 : (start.id - 1)
                                        addOffset = Int32(-selectedLimit)
                                        maxId = end.id
                                        minId = start.id - 1
                                        
                                        let rangeStartId = start.id
                                        let rangeEndId = min(end.id, Int32.max - 1)
                                        if rangeStartId <= rangeEndId {
                                            minMaxRange = rangeStartId ... rangeEndId
                                        } else {
                                            minMaxRange = rangeStartId ... rangeStartId
                                            assertionFailure()
                                        }
                                    } else {
                                        offsetId = start.id == Int32.max ? start.id : (start.id + 1)
                                        addOffset = 0
                                        maxId = start.id == Int32.max ? start.id : (start.id + 1)
                                        minId = end.id
                                        
                                        let rangeStartId = end.id
                                        let rangeEndId = min(start.id, Int32.max - 1)
                                        if rangeStartId <= rangeEndId {
                                            minMaxRange = rangeStartId ... rangeEndId
                                        } else {
                                            minMaxRange = rangeStartId ... rangeStartId
                                            assertionFailure()
                                        }
                                    }
                                case let .aroundId(id):
                                    offsetId = id.id
                                    addOffset = Int32(-selectedLimit / 2)
                                    maxId = Int32.max
                                    minId = 1
                                
                                    minMaxRange = 1 ... Int32.max - 1
                            }
                            // Api.functions.messages.getUnreadMentions
                            request = source.request(Api.functions.messages.getUnreadMentions(peer: inputPeer, offsetId: offsetId, addOffset: addOffset, limit: Int32(selectedLimit), maxId: maxId, minId: minId))
                        } else if tag == .liveLocation {
                            let selectedLimit = limit
                            
                            switch direction {
                                case .aroundId, .range:
                                    implicitelyFillHole = true
                            }
                            minMaxRange = 1 ... (Int32.max - 1)
                          // Api.functions.messages.getRecentLocations
                            request = source.request(Api.functions.messages.getRecentLocations(peer: inputPeer, limit: Int32(selectedLimit), hash: 0))
                        } else if let filter = messageFilterForTagMask(tag) {
                            let offsetId: Int32
                            let addOffset: Int32
                            let selectedLimit = limit
                            let maxId: Int32
                            let minId: Int32
                            
                            switch direction {
                                case let .range(start, end):
                                    if start.id <= end.id {
                                        offsetId = start.id <= 1 ? 1 : (start.id - 1)
                                        addOffset = Int32(-selectedLimit)
                                        maxId = end.id
                                        minId = start.id - 1
                                        
                                        let rangeStartId = start.id
                                        let rangeEndId = min(end.id, Int32.max - 1)
                                        if rangeStartId <= rangeEndId {
                                            minMaxRange = rangeStartId ... rangeEndId
                                        } else {
                                            minMaxRange = rangeStartId ... rangeStartId
                                            assertionFailure()
                                        }
                                    } else {
                                        offsetId = start.id == Int32.max ? start.id : (start.id + 1)
                                        addOffset = 0
                                        maxId = start.id == Int32.max ? start.id : (start.id + 1)
                                        minId = end.id
                                        
                                        let rangeStartId = end.id
                                        let rangeEndId = min(start.id, Int32.max - 1)
                                        if rangeStartId <= rangeEndId {
                                            minMaxRange = rangeStartId ... rangeEndId
                                        } else {
                                            minMaxRange = rangeStartId ... rangeStartId
                                            assertionFailure()
                                        }
                                    }
                                case let .aroundId(id):
                                    offsetId = id.id
                                    addOffset = Int32(-selectedLimit / 2)
                                    maxId = Int32.max
                                    minId = 1
                                
                                    minMaxRange = 1 ... (Int32.max - 1)
                            }
                            
                          // Api.functions.messages.search
                            request = source.request(Api.functions.messages.search(flags: 0, peer: inputPeer, q: "", fromId: nil, filter: filter, minDate: 0, maxDate: 0, offsetId: offsetId, addOffset: addOffset, limit: Int32(selectedLimit), maxId: maxId, minId: minId, hash: 0))
                        } else {
                            assertionFailure()
                            minMaxRange = 1 ... 1
                            request = .never()
                    }
                }
                
                return request
                |> retryRequest
                |> mapToSignal { result -> Signal<Never, NoError> in
                    let messages: [Api.Message]
                    let chats: [Api.Chat]
                    let users: [Api.User]
                    var channelPts: Int32?
                    switch result {
                        case let .messages(messages: apiMessages, chats: apiChats, users: apiUsers):
                            messages = apiMessages
                            chats = apiChats
                            users = apiUsers
                        case let .messagesSlice(_, _, _, messages: apiMessages, chats: apiChats, users: apiUsers):
                            messages = apiMessages
                            chats = apiChats
                            users = apiUsers
                        case let .channelMessages(_, pts, _, apiMessages, apiChats, apiUsers):
                            messages = apiMessages
                            chats = apiChats
                            users = apiUsers
                            channelPts = pts
                        case .messagesNotModified:
                            messages = []
                            chats = []
                            users = []
                    }
                    
                    var peers: [Peer] = []
                    var peerPresences: [PeerId: PeerPresence] = [:]
                    for chat in chats {
                        if let groupOrChannel = parseTelegramGroupOrChannel(chat: chat) {
                            peers.append(groupOrChannel)
                        }
                    }
                    for user in users {
                        let telegramUser = TelegramUser(user: user)
                        peers.append(telegramUser)
                        if let presence = TelegramUserPresence(apiUser: user) {
                            peerPresences[telegramUser.id] = presence
                        }
                    }
                    
                    var storeMessages: [StoreMessage] = []
                    
                    for message in messages {
                        if let storeMessage = StoreMessage(apiMessage: message, namespace: namespace) {
                            if let channelPts = channelPts {
                                var attributes = storeMessage.attributes
                                attributes.append(ChannelMessageStateVersionAttribute(pts: channelPts))
                                storeMessages.append(storeMessage.withUpdatedAttributes(attributes))
                            } else {
                                storeMessages.append(storeMessage)
                            }
                        }
                    }
                    
                    return withResolvedAssociatedMessages(postbox: postbox, source: source, peers: Dictionary(peers.map({ ($0.id, $0) }), uniquingKeysWith: { lhs, _ in lhs }), storeMessages: storeMessages, { transaction, additionalPeers, additionalMessages in
                    // addMessages location: .Random
                        let _ = transaction.addMessages(storeMessages, location: .Random)
                        let _ = transaction.addMessages(additionalMessages, location: .Random)
                        let filledRange: ClosedRange<MessageId.Id>
                        let ids = messages.compactMap({ $0.id()?.id })
                        if ids.count == 0 || implicitelyFillHole {
                            filledRange = minMaxRange
                        } else {
                            let messageRange = ids.min()! ... ids.max()!
                            switch direction {
                                case let .aroundId(aroundId):
                                    filledRange = min(aroundId.id, messageRange.lowerBound) ... max(aroundId.id, messageRange.upperBound)
                                case let .range(start, end):
                                    if start.id <= end.id {
                                        let minBound = start.id
                                        let maxBound = messageRange.upperBound
                                        filledRange = min(minBound, maxBound) ... max(minBound, maxBound)
                                    } else {
                                        let minBound = messageRange.lowerBound
                                        let maxBound = start.id
                                        filledRange = min(minBound, maxBound) ... max(minBound, maxBound)
                                    }
                            }
                        }
                        // remove message hole in filledRange
                        transaction.removeHole(peerId: peerId, namespace: namespace, space: space, range: filledRange)
                        
                        // update peers
                        updatePeers(transaction: transaction, peers: peers + additionalPeers, update: { _, updated -> Peer in
                            return updated
                        })
                        
                        // update peer presences
                        updatePeerPresences(transaction: transaction, accountPeerId: accountPeerId, peerPresences: peerPresences)
                        
                        print("fetchMessageHistoryHole for \(peer.debugDisplayTitle) space \(space) done")
                        
                        return
                    })
                }
            } else {
                return .complete()
            }
        }
    }
}

withResolvedAssociatedMessages

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
func withResolvedAssociatedMessages(postbox: Postbox, source: FetchMessageHistoryHoleSource, peers: [PeerId: Peer], storeMessages: [StoreMessage], _ f: @escaping (Transaction, [Peer], [StoreMessage]) -> Void) -> Signal<Never, NoError> {
    return postbox.transaction { transaction -> Signal<Never, NoError> in
        var storedIds = Set<MessageId>()
        var referencedIds = Set<MessageId>()
        for message in storeMessages {
            guard case let .Id(id) = message.id else {
                continue
            }
            storedIds.insert(id)
            for attribute in message.attributes {
                referencedIds.formUnion(attribute.associatedMessageIds)
            }
        }
        referencedIds.subtract(storedIds)
        referencedIds.subtract(transaction.filterStoredMessageIds(referencedIds))
        
        if referencedIds.isEmpty {
            f(transaction, [], [])
            return .complete()
        } else {
            var signals: [Signal<([Api.Message], [Api.Chat], [Api.User]), NoError>] = []
            for (peerId, messageIds) in messagesIdsGroupedByPeerId(referencedIds) {
                if let peer = transaction.getPeer(peerId) ?? peers[peerId] {
                    var signal: Signal<Api.messages.Messages, MTRpcError>?
                    if peerId.namespace == Namespaces.Peer.CloudUser || peerId.namespace == Namespaces.Peer.CloudGroup {
                      // Api.functions.messages.getMessages
                        signal = source.request(Api.functions.messages.getMessages(id: messageIds.map({ Api.InputMessage.inputMessageID(id: $0.id) })))
                    } else if peerId.namespace == Namespaces.Peer.CloudChannel {
                        if let inputChannel = apiInputChannel(peer) {
                          // Api.functions.channels.getMessages
                            signal = source.request(Api.functions.channels.getMessages(channel: inputChannel, id: messageIds.map({ Api.InputMessage.inputMessageID(id: $0.id) })))
                        }
                    }
                    if let signal = signal {
                        signals.append(signal
                        |> map { result in
                            switch result {
                                case let .messages(messages, chats, users):
                                    return (messages, chats, users)
                                case let .messagesSlice(_, _, _, messages, chats, users):
                                    return (messages, chats, users)
                                case let .channelMessages(_, _, _, messages, chats, users):
                                    return (messages, chats, users)
                                case .messagesNotModified:
                                    return ([], [], [])
                            }
                        }
                        |> `catch` { _ in
                            return Signal<([Api.Message], [Api.Chat], [Api.User]), NoError>.single(([], [], []))
                        })
                    }
                }
            }
            
            let fetchMessages = combineLatest(signals)
            
            return fetchMessages
            |> mapToSignal { results -> Signal<Never, NoError> in
                var additionalPeers: [Peer] = []
                var additionalMessages: [StoreMessage] = []
                for (messages, chats, users) in results {
                    if !messages.isEmpty {
                        for message in messages {
                            if let message = StoreMessage(apiMessage: message) {
                                additionalMessages.append(message)
                            }
                        }
                    }
                    for chat in chats {
                        if let peer = parseTelegramGroupOrChannel(chat: chat) {
                            additionalPeers.append(peer)
                        }
                    }
                    for user in users {
                        additionalPeers.append(TelegramUser(user: user))
                    }
                }
                return postbox.transaction { transaction -> Void in
                    f(transaction, additionalPeers, additionalMessages)
                }
                |> ignoreValues
            }
        }
    }
    |> switchToLatest
}
This post is licensed under CC BY 4.0 by the author.