-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathMXThreadingService.swift
More file actions
422 lines (374 loc) · 17.1 KB
/
Copy pathMXThreadingService.swift
File metadata and controls
422 lines (374 loc) · 17.1 KB
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
//
// Copyright 2021 The Matrix.org Foundation C.I.C
//
// 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 Foundation
/// MXThreadingService error
public enum MXThreadingServiceError: Int, Error {
case sessionNotFound
case unknown
}
// MARK: - MXThreadingService errors
extension MXThreadingServiceError: CustomNSError {
public static let errorDomain = "org.matrix.sdk.threadingservice"
public var errorCode: Int {
return rawValue
}
public var errorUserInfo: [String: Any] {
return [:]
}
}
@objc
public protocol MXThreadingServiceDelegate: AnyObject {
/// Delegate method to be called when thread are updated in any way.
@objc optional func threadingServiceDidUpdateThreads(_ service: MXThreadingService)
/// Delegate method to be called when a new local thread is created
@objc optional func threadingService(_ service: MXThreadingService,
didCreateNewThread thread: MXThread,
direction: MXTimelineDirection)
}
@objcMembers
/// Threading service class.
public class MXThreadingService: NSObject {
private weak var session: MXSession?
private let lockThreads = NSRecursiveLock()
private var threads: [String: MXThread] = [:]
private let multicastDelegate: MXMulticastDelegate<MXThreadingServiceDelegate> = MXMulticastDelegate()
/// Initializer
/// - Parameter session: session instance
public init(withSession session: MXSession) {
self.session = session
super.init()
}
/// Handle joined room sync
/// - Parameter roomSync: room sync instance
public func handleJoinedRoomSync(_ roomSync: MXRoomSync, forRoom roomId: String) {
guard let session = session else {
// session closed
return
}
let events = roomSync.timeline.events
// Make sure that all events have a room id. They are skipped in some server responses
events.forEach({ $0.roomId = roomId })
session.decryptEvents(events, inTimeline: nil) { _ in
let dispatchGroup = DispatchGroup()
for event in events {
dispatchGroup.enter()
self.handleEvent(event, direction: .forwards) { _ in
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
self.threads.values.filter { $0.roomId == roomId }.forEach { $0.handleJoinedRoomSync(roomSync) }
}
}
}
/// Adds event to the related thread instance
/// - Parameters:
/// - event: event to be handled
/// - direction: direction of the event
/// - completion: Completion block containing the flag indicating that the event is handled
public func handleEvent(_ event: MXEvent, direction: MXTimelineDirection, completion: ((Bool) -> Void)?) {
guard let session = session else {
// session closed
completion?(false)
return
}
if event.isInThread() {
// event is in a thread
handleInThreadEvent(event, direction: direction, session: session, completion: completion)
} else if let thread = thread(withId: event.eventId) {
// event is a thread root
if thread.addEvent(event, direction: direction) {
notifyDidUpdateThreads()
completion?(true)
} else {
completion?(false)
}
} else if event.isEdit() {
handleEditEvent(event, direction: direction, session: session, completion: completion)
} else if event.eventType == .roomRedaction {
handleRedactionEvent(event, direction: direction, session: session, completion: completion)
} else {
completion?(false)
}
}
/// Get notifications count of threads in a room
/// - Parameter roomId: Room identifier
/// - Returns: Notifications count
public func notificationsCount(forRoom roomId: String) -> MXThreadNotificationsCount {
let notified = unsortedParticipatedThreads(inRoom: roomId).filter { $0.notificationCount > 0 }.count
let highlighted = unsortedThreads(inRoom: roomId).filter { $0.highlightCount > 0 }.count
return MXThreadNotificationsCount(numberOfNotifiedThreads: UInt(notified),
numberOfHighlightedThreads: UInt(highlighted))
}
/// Method to check an event is a thread root or not
/// - Parameter event: event to be checked
/// - Returns: true is given event is a thread root
public func isEventThreadRoot(_ event: MXEvent) -> Bool {
return thread(withId: event.eventId) != nil
}
/// Method to get a thread with specific identifier
/// - Parameter identifier: identifier of a thread
/// - Returns: thread instance if found, nil otherwise
public func thread(withId identifier: String) -> MXThread? {
lockThreads.lock()
defer { lockThreads.unlock() }
return threads[identifier]
}
public func createTempThread(withId identifier: String, roomId: String) -> MXThread {
guard let session = session else {
fatalError("Session must be available")
}
return MXThread(withSession: session, identifier: identifier, roomId: roomId)
}
/// Mark a thread as read
/// - Parameter threadId: Thread id
public func markThreadAsRead(_ threadId: String) {
guard let thread = thread(withId: threadId) else {
return
}
thread.markAsRead()
notifyDidUpdateThreads()
}
@discardableResult
public func allThreads(inRoom roomId: String,
onlyParticipated: Bool = false,
completion: @escaping (MXResponse<[MXThreadProtocol]>) -> Void) -> MXHTTPOperation? {
guard let session = session else {
DispatchQueue.main.async {
completion(.failure(MXThreadingServiceError.sessionNotFound))
}
return nil
}
var serverSupportThreads = false
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let operation = session.supportedMatrixVersions { response in
switch response {
case .success(let versions):
serverSupportThreads = versions.supportsThreads
default:
break
}
dispatchGroup.leave()
}
dispatchGroup.notify(queue: .main) {
if serverSupportThreads {
// homeserver supports threads
let filter = MXRoomEventFilter()
filter.relatedByTypes = [MXEventRelationTypeThread]
if onlyParticipated {
filter.relatedBySenders = [session.myUserId]
}
let newOperation = session.matrixRestClient.messages(forRoom: roomId,
from: "",
direction: .backwards,
limit: nil,
filter: filter) { response in
switch response {
case .success(let paginationResponse):
guard let rootEvents = paginationResponse.chunk else {
completion(.success([]))
return
}
session.decryptEvents(rootEvents, inTimeline: nil) { _ in
let threads = rootEvents.map { self.thread(forRootEvent: $0, session: session) }.sorted(by: <)
let decryptionGroup = DispatchGroup()
for thread in threads {
if let rootEvent = rootEvents.first(where: { $0.eventId == thread.id }),
let latestEvent = rootEvent.unsignedData.relations?.thread?.latestEvent {
decryptionGroup.enter()
session.decryptEvents([latestEvent], inTimeline: nil) { _ in
thread.updateLastMessage(latestEvent)
decryptionGroup.leave()
}
}
}
decryptionGroup.notify(queue: .main) {
completion(.success(threads))
}
}
case .failure(let error):
completion(.failure(error))
}
}
operation.mutate(to: newOperation)
} else {
// use local implementation
if onlyParticipated {
completion(.success(self.localParticipatedThreads(inRoom: roomId)))
} else {
completion(.success(self.localThreads(inRoom: roomId)))
}
}
}
return operation
}
// MARK: - Private
private func localThreads(inRoom roomId: String) -> [MXThreadProtocol] {
// sort threads so that the newer is the first
return unsortedThreads(inRoom: roomId).sorted(by: <)
}
private func localParticipatedThreads(inRoom roomId: String) -> [MXThreadProtocol] {
// filter only participated threads and then sort threads so that the newer is the first
return unsortedParticipatedThreads(inRoom: roomId).sorted(by: <)
}
private func thread(forRootEvent rootEvent: MXEvent, session: MXSession) -> MXThreadModel {
var notificationCount: UInt = 0
var highlightCount: UInt = 0
if let store = session.store {
notificationCount = store.localUnreadEventCount(rootEvent.roomId,
threadId: rootEvent.eventId,
withTypeIn: session.unreadEventTypes)
let newEvents = store.newIncomingEvents(inRoom: rootEvent.roomId,
threadId: rootEvent.eventId,
withTypeIn: session.unreadEventTypes)
highlightCount = UInt(newEvents.filter { $0.shouldBeHighlighted(inSession: session) }.count)
}
if let localThread = thread(withId: rootEvent.eventId) {
notificationCount = max(notificationCount, localThread.notificationCount)
highlightCount = max(highlightCount, localThread.highlightCount)
}
let thread = MXThreadModel(withRootEvent: rootEvent,
notificationCount: notificationCount,
highlightCount: highlightCount)
// workaround for https://github.com/matrix-org/synapse/issues/11753. Can be removed when that's fixed.
if thread.numberOfReplies == 0, let localThread = self.thread(withId: rootEvent.eventId) {
if let lastMessage = localThread.lastMessage {
thread.updateLastMessage(lastMessage)
}
thread.updateNumberOfReplies(localThread.numberOfReplies)
}
return thread
}
private func handleInThreadEvent(_ event: MXEvent, direction: MXTimelineDirection, session: MXSession, completion: ((Bool) -> Void)?) {
guard let threadId = event.threadId else {
completion?(false)
return
}
if let thread = thread(withId: threadId) {
// add event to the thread if found
let handled = thread.addEvent(event, direction: direction)
notifyDidUpdateThreads()
completion?(handled)
} else {
// create the thread for the first time
let thread = MXThread(withSession: session, identifier: threadId, roomId: event.roomId)
self.saveThread(thread)
self.notifyDidCreateThread(thread, direction: direction)
self.notifyDidUpdateThreads()
let dispatchGroup = DispatchGroup()
// try to find the root event in the session store
dispatchGroup.enter()
session.event(withEventId: threadId, inRoom: event.roomId) { response in
switch response {
case .success(let rootEvent):
thread.addEvent(rootEvent, direction: direction)
case .failure(let error):
MXLog.error("[MXThreadingService] handleInThreadEvent: root event not found: \(error)")
}
dispatchGroup.leave()
}
dispatchGroup.notify(queue: .main) {
let handled = thread.addEvent(event, direction: direction)
self.notifyDidUpdateThreads()
completion?(handled)
}
}
}
private func handleEditEvent(_ event: MXEvent, direction: MXTimelineDirection, session: MXSession, completion: ((Bool) -> Void)?) {
guard let editedEventId = event.relatesTo?.eventId else {
completion?(false)
return
}
guard let editedEvent = session.store?.event(withEventId: editedEventId,
inRoom: event.roomId) else {
completion?(false)
return
}
handleEvent(editedEvent, direction: direction) { _ in
guard let newEvent = editedEvent.editedEvent(fromReplacementEvent: event) else {
completion?(false)
return
}
if let threadId = editedEvent.threadId,
let thread = self.thread(withId: threadId) {
// edited event is in a known thread
let handled = thread.replaceEvent(withId: editedEventId, with: newEvent)
self.notifyDidUpdateThreads()
completion?(handled)
return
} else if let thread = self.thread(withId: editedEventId) {
// edited event is a thread root
let handled = thread.replaceEvent(withId: editedEventId, with: newEvent)
self.notifyDidUpdateThreads()
completion?(handled)
return
}
completion?(false)
}
}
private func handleRedactionEvent(_ event: MXEvent, direction: MXTimelineDirection, session: MXSession, completion: ((Bool) -> Void)?) {
guard direction == .forwards else {
completion?(false)
return
}
if let redactedEventId = event.redacts,
let thread = thread(withId: redactedEventId),
let newEvent = session.store?.event(withEventId: redactedEventId,
inRoom: event.roomId) {
session.decryptEvents([newEvent], inTimeline: nil) { _ in
// event is a thread root
let handled = thread.replaceEvent(withId: redactedEventId, with: newEvent)
self.notifyDidUpdateThreads()
completion?(handled)
}
return
}
completion?(false)
}
private func unsortedThreads(inRoom roomId: String) -> [MXThread] {
return Array(threads.values).filter({ $0.roomId == roomId })
}
private func unsortedParticipatedThreads(inRoom roomId: String) -> [MXThread] {
return Array(threads.values).filter({ $0.roomId == roomId && $0.isParticipated })
}
private func saveThread(_ thread: MXThread) {
lockThreads.lock()
defer { lockThreads.unlock() }
threads[thread.id] = thread
}
// MARK: - Delegate
/// Add delegate instance
/// - Parameter delegate: delegate instance
public func addDelegate(_ delegate: MXThreadingServiceDelegate) {
multicastDelegate.addDelegate(delegate)
}
/// Remove delegate instance
/// - Parameter delegate: delegate instance
public func removeDelegate(_ delegate: MXThreadingServiceDelegate) {
multicastDelegate.removeDelegate(delegate)
}
/// Remove all delegates
public func removeAllDelegates() {
multicastDelegate.removeAllDelegates()
}
private func notifyDidUpdateThreads() {
multicastDelegate.invoke({ $0.threadingServiceDidUpdateThreads?(self) })
}
private func notifyDidCreateThread(_ thread: MXThread, direction: MXTimelineDirection) {
multicastDelegate.invoke({ $0.threadingService?(self, didCreateNewThread: thread, direction: direction) })
}
}