generated from element-hq/.github
-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathRoomSummaryProvider.swift
439 lines (369 loc) · 18.1 KB
/
RoomSummaryProvider.swift
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
import Foundation
import MatrixRustSDK
class RoomSummaryProvider: RoomSummaryProviderProtocol {
private let roomListService: RoomListServiceProtocol
private let eventStringBuilder: RoomEventStringBuilder
private let name: String
private let shouldUpdateVisibleRange: Bool
private let notificationSettings: NotificationSettingsProxyProtocol
private let roomListPageSize = 200
private let serialDispatchQueue: DispatchQueue
// periphery:ignore - retaining purpose
private var roomList: RoomListProtocol?
private var cancellables = Set<AnyCancellable>()
private var listUpdatesSubscriptionResult: RoomListEntriesWithDynamicAdaptersResult?
private var listUpdatesTaskHandle: TaskHandle?
private var stateUpdatesTaskHandle: TaskHandle?
private let roomListSubject = CurrentValueSubject<[RoomSummary], Never>([])
private let stateSubject = CurrentValueSubject<RoomSummaryProviderState, Never>(.notLoaded)
private let diffsPublisher = PassthroughSubject<[RoomListEntriesUpdate], Never>()
var roomListPublisher: CurrentValuePublisher<[RoomSummary], Never> {
roomListSubject.asCurrentValuePublisher()
}
var statePublisher: CurrentValuePublisher<RoomSummaryProviderState, Never> {
stateSubject.asCurrentValuePublisher()
}
private var rooms: [RoomSummary] = [] {
didSet {
roomListSubject.send(rooms)
}
}
/// Build a new summary provider with the given parameters
/// - Parameters:
/// - shouldUpdateVisibleRange: whether this summary provider should foward visible ranges
/// to the room list service through the `applyInput(input: .viewport(ranges` api. Only useful for
/// lists that need to update the visible range on Sliding Sync
init(roomListService: RoomListServiceProtocol,
eventStringBuilder: RoomEventStringBuilder,
name: String,
shouldUpdateVisibleRange: Bool = false,
notificationSettings: NotificationSettingsProxyProtocol) {
self.roomListService = roomListService
serialDispatchQueue = DispatchQueue(label: "io.element.elementx.roomsummaryprovider", qos: .default)
self.eventStringBuilder = eventStringBuilder
self.name = name
self.shouldUpdateVisibleRange = shouldUpdateVisibleRange
self.notificationSettings = notificationSettings
diffsPublisher
.receive(on: serialDispatchQueue)
.sink { [weak self] in self?.updateRoomsWithDiffs($0) }
.store(in: &cancellables)
setupNotificationSettingsSubscription()
}
func setRoomList(_ roomList: RoomList) {
guard listUpdatesTaskHandle == nil, stateUpdatesTaskHandle == nil else {
return
}
self.roomList = roomList
do {
listUpdatesSubscriptionResult = roomList.entriesWithDynamicAdapters(pageSize: UInt32(roomListPageSize), listener: RoomListEntriesListenerProxy { [weak self] updates in
guard let self else { return }
MXLog.verbose("\(name): Received list update")
diffsPublisher.send(updates)
})
// Forces the listener above to be called with the current state
setFilter(.all(filters: []))
listUpdatesTaskHandle = listUpdatesSubscriptionResult?.entriesStream
let stateUpdatesSubscriptionResult = try roomList.loadingState(listener: RoomListStateObserver { [weak self] state in
guard let self else { return }
MXLog.info("\(name): Received state update: \(state)")
stateSubject.send(RoomSummaryProviderState(roomListState: state))
})
stateUpdatesTaskHandle = stateUpdatesSubscriptionResult.stateStream
stateSubject.send(RoomSummaryProviderState(roomListState: stateUpdatesSubscriptionResult.state))
} catch {
MXLog.error("Failed setting up room list entry listener with error: \(error)")
}
}
func updateVisibleRange(_ range: Range<Int>) {
if range.upperBound >= rooms.count {
listUpdatesSubscriptionResult?.controller.addOnePage()
} else if range.lowerBound == 0 {
listUpdatesSubscriptionResult?.controller.resetToOnePage()
}
guard shouldUpdateVisibleRange else {
return
}
Task {
do {
// The scroll view content size based visible range calculations might create large ranges
// This is just a safety check to not overload the backend
var upperBound = range.upperBound
if range.upperBound - range.lowerBound > SlidingSyncConstants.maximumVisibleRangeSize {
upperBound = range.lowerBound + SlidingSyncConstants.maximumVisibleRangeSize
}
MXLog.info("\(name): Setting visible range to \(range.lowerBound)...\(upperBound)")
try await roomListService.applyInput(input: .viewport(ranges: [.init(start: UInt32(range.lowerBound), endInclusive: UInt32(upperBound))]))
} catch {
MXLog.error("Failed updating visible range with error: \(error)")
}
}
}
func setFilter(_ filter: RoomSummaryProviderFilter) {
switch filter {
case .excludeAll:
_ = listUpdatesSubscriptionResult?.controller.setFilter(kind: .none)
case let .search(query):
let filters: [RoomListEntriesDynamicFilterKind] = [.normalizedMatchRoomName(pattern: query), .nonLeft]
_ = listUpdatesSubscriptionResult?.controller.setFilter(kind: .all(filters: filters))
case let .all(filters):
var filters = filters.map(\.rustFilter)
filters.append(.nonLeft)
_ = listUpdatesSubscriptionResult?.controller.setFilter(kind: .all(filters: filters))
}
}
// MARK: - Private
fileprivate func updateRoomsWithDiffs(_ diffs: [RoomListEntriesUpdate]) {
let span = MXLog.createSpan("\(name).process_room_list_diffs")
span.enter()
defer {
span.exit()
}
MXLog.info("Started processing room list diffs")
MXLog.verbose("\(name): Received \(diffs.count) diffs, current room list \(rooms.compactMap { $0.id ?? "Empty" })")
rooms = diffs.reduce(rooms) { currentItems, diff in
processDiff(diff, on: currentItems)
}
MXLog.verbose("\(name): Finished applying \(diffs.count) diffs, new room list \(rooms.compactMap { $0.id ?? "Empty" })")
MXLog.info("Finished processing room list diffs")
}
private func processDiff(_ diff: RoomListEntriesUpdate, on currentItems: [RoomSummary]) -> [RoomSummary] {
guard let collectionDiff = buildDiff(from: diff, on: currentItems) else {
MXLog.error("\(name): Failed building CollectionDifference from \(diff)")
return currentItems
}
guard let updatedItems = currentItems.applying(collectionDiff) else {
MXLog.error("\(name): Failed applying diff: \(collectionDiff)")
return currentItems
}
return updatedItems
}
private func fetchRoomInfo(roomListItem: RoomListItemProtocol) -> RoomInfo? {
class FetchResult {
var roomInfo: RoomInfo?
}
let semaphore = DispatchSemaphore(value: 0)
let result = FetchResult()
Task {
do {
result.roomInfo = try await roomListItem.roomInfo()
} catch {
MXLog.error("Failed fetching room info with error: \(error)")
}
semaphore.signal()
}
semaphore.wait()
return result.roomInfo
}
private func buildRoomSummaryForIdentifier(_ identifier: String, invalidated: Bool) -> RoomSummary {
guard let roomListItem = try? roomListService.room(roomId: identifier) else {
MXLog.error("\(name): Failed finding room with id: \(identifier)")
return .empty
}
guard let roomInfo = fetchRoomInfo(roomListItem: roomListItem) else {
return .empty
}
var attributedLastMessage: AttributedString?
var lastMessageFormattedTimestamp: String?
if let latestRoomMessage = roomInfo.latestEvent {
let lastMessage = EventTimelineItemProxy(item: latestRoomMessage, id: 0)
lastMessageFormattedTimestamp = lastMessage.timestamp.formattedMinimal()
attributedLastMessage = eventStringBuilder.buildAttributedString(for: lastMessage)
}
var inviterProxy: RoomMemberProxyProtocol?
if let inviter = roomInfo.inviter {
inviterProxy = RoomMemberProxy(member: inviter)
}
let notificationMode = roomInfo.userDefinedNotificationMode.flatMap { RoomNotificationModeProxy.from(roomNotificationMode: $0) }
let details = RoomSummaryDetails(id: roomInfo.id,
isInvite: roomInfo.membership == .invited,
inviter: inviterProxy,
name: roomInfo.name ?? roomInfo.id,
isDirect: roomInfo.isDirect,
avatarURL: roomInfo.avatarUrl.flatMap(URL.init(string:)),
lastMessage: attributedLastMessage,
lastMessageFormattedTimestamp: lastMessageFormattedTimestamp,
unreadMessagesCount: UInt(roomInfo.numUnreadMessages),
unreadMentionsCount: UInt(roomInfo.numUnreadMentions),
unreadNotificationsCount: UInt(roomInfo.numUnreadNotifications),
notificationMode: notificationMode,
canonicalAlias: roomInfo.canonicalAlias,
hasOngoingCall: roomInfo.hasRoomCall,
isMarkedUnread: roomInfo.isMarkedUnread,
isFavourite: roomInfo.isFavourite)
return invalidated ? .invalidated(details: details) : .filled(details: details)
}
private func buildSummaryForRoomListEntry(_ entry: RoomListEntry) -> RoomSummary {
switch entry {
case .empty:
return .empty
case .filled(let roomId):
return buildRoomSummaryForIdentifier(roomId, invalidated: false)
case .invalidated(let roomId):
guard let cachedRoom = rooms.first(where: { $0.id == roomId }) else {
return buildRoomSummaryForIdentifier(roomId, invalidated: true)
}
switch cachedRoom {
case .empty:
return .empty
case .filled(let details):
return .invalidated(details: details)
case .invalidated:
return cachedRoom
}
}
}
private func buildDiff(from diff: RoomListEntriesUpdate, on rooms: [RoomSummary]) -> CollectionDifference<RoomSummary>? {
var changes = [CollectionDifference<RoomSummary>.Change]()
switch diff {
case .append(let values):
let debugIdentifiers = values.map(\.debugIdentifier)
MXLog.verbose("\(name): Append \(debugIdentifiers)")
for (index, value) in values.enumerated() {
let summary = buildSummaryForRoomListEntry(value)
changes.append(.insert(offset: rooms.count + index, element: summary, associatedWith: nil))
}
case .clear:
MXLog.verbose("\(name): Clear all items")
for (index, value) in rooms.enumerated() {
changes.append(.remove(offset: index, element: value, associatedWith: nil))
}
case .insert(let index, let value):
MXLog.verbose("\(name): Insert at \(value.debugIdentifier) at \(index)")
let summary = buildSummaryForRoomListEntry(value)
changes.append(.insert(offset: Int(index), element: summary, associatedWith: nil))
case .popBack:
MXLog.verbose("\(name): Pop Back")
guard let value = rooms.last else {
fatalError()
}
changes.append(.remove(offset: rooms.count - 1, element: value, associatedWith: nil))
case .popFront:
MXLog.verbose("\(name): Pop Front")
let summary = rooms[0]
changes.append(.remove(offset: 0, element: summary, associatedWith: nil))
case .pushBack(let value):
MXLog.verbose("\(name): Push Back \(value.debugIdentifier)")
let summary = buildSummaryForRoomListEntry(value)
changes.append(.insert(offset: rooms.count, element: summary, associatedWith: nil))
case .pushFront(let value):
MXLog.verbose("\(name): Push Front \(value.debugIdentifier)")
let summary = buildSummaryForRoomListEntry(value)
changes.append(.insert(offset: 0, element: summary, associatedWith: nil))
case .remove(let index):
let summary = rooms[Int(index)]
MXLog.verbose("\(name): Remove \(summary.id ?? "") from \(index)")
changes.append(.remove(offset: Int(index), element: summary, associatedWith: nil))
case .reset(let values):
let debugIdentifiers = values.map(\.debugIdentifier)
MXLog.verbose("\(name): Replace all items with \(debugIdentifiers)")
for (index, summary) in rooms.enumerated() {
changes.append(.remove(offset: index, element: summary, associatedWith: nil))
}
for (index, value) in values.enumerated() {
changes.append(.insert(offset: index, element: buildSummaryForRoomListEntry(value), associatedWith: nil))
}
case .set(let index, let value):
MXLog.verbose("\(name): Update \(value.debugIdentifier) at \(index)")
let summary = buildSummaryForRoomListEntry(value)
changes.append(.remove(offset: Int(index), element: summary, associatedWith: nil))
changes.append(.insert(offset: Int(index), element: summary, associatedWith: nil))
case .truncate(let length):
for (index, value) in rooms.enumerated() {
if index < length {
continue
}
changes.append(.remove(offset: index, element: value, associatedWith: nil))
}
}
return CollectionDifference(changes)
}
private func setupNotificationSettingsSubscription() {
notificationSettings.callbacks
.receive(on: serialDispatchQueue)
.dropFirst() // drop the first one to avoid rebuilding the summaries during the first synchronization
.sink { [weak self] callback in
guard let self else { return }
switch callback {
case .settingsDidChange:
self.rebuildRoomSummaries()
}
}
.store(in: &cancellables)
}
private func rebuildRoomSummaries() {
let span = MXLog.createSpan("\(name).rebuild_room_summaries")
span.enter()
defer {
span.exit()
}
MXLog.info("\(name): Rebuilding room summaries for \(rooms.count) rooms")
rooms = rooms.map {
switch $0 {
case .empty:
return $0
case .filled(let details):
return self.buildRoomSummaryForIdentifier(details.id, invalidated: false)
case .invalidated(let details):
return self.buildRoomSummaryForIdentifier(details.id, invalidated: true)
}
}
MXLog.info("\(name): Finished rebuilding room summaries (\(rooms.count) rooms)")
}
}
extension RoomSummaryProviderState {
init(roomListState: RoomListLoadingState) {
switch roomListState {
case .notLoaded:
self = .notLoaded
case .loaded(let maximumNumberOfRooms):
self = .loaded(totalNumberOfRooms: UInt(maximumNumberOfRooms ?? 0))
}
}
}
extension MatrixRustSDK.RoomListEntry {
var debugIdentifier: String {
switch self {
case .empty:
return "Empty"
case .invalidated(let roomId):
return "Invalidated(\(roomId))"
case .filled(let roomId):
return "Filled(\(roomId))"
}
}
}
private class RoomListEntriesListenerProxy: RoomListEntriesListener {
private let onUpdateClosure: ([RoomListEntriesUpdate]) -> Void
init(_ onUpdateClosure: @escaping ([RoomListEntriesUpdate]) -> Void) {
self.onUpdateClosure = onUpdateClosure
}
func onUpdate(roomEntriesUpdate: [RoomListEntriesUpdate]) {
onUpdateClosure(roomEntriesUpdate)
}
}
private class RoomListStateObserver: RoomListLoadingStateListener {
private let onUpdateClosure: (RoomListLoadingState) -> Void
init(_ onUpdateClosure: @escaping (RoomListLoadingState) -> Void) {
self.onUpdateClosure = onUpdateClosure
}
func onUpdate(state: RoomListLoadingState) {
onUpdateClosure(state)
}
}