generated from element-hq/.github
-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathTimelineProxy.swift
635 lines (513 loc) · 24.8 KB
/
TimelineProxy.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//
// Copyright 2023 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
final class TimelineProxy: TimelineProxyProtocol {
private let timeline: Timeline
private var backPaginationStatusObservationToken: TaskHandle?
// The default values don't matter here, they will be updated when calling subscribeToPagination.
private let backPaginationStatusSubject = CurrentValueSubject<PaginationStatus, Never>(.timelineEndReached)
private let forwardPaginationStatusSubject = CurrentValueSubject<PaginationStatus, Never>(.timelineEndReached)
let isLive: Bool
private var innerTimelineProvider: RoomTimelineProviderProtocol!
var timelineProvider: RoomTimelineProviderProtocol {
innerTimelineProvider
}
deinit {
backPaginationStatusObservationToken?.cancel()
}
init(timeline: Timeline, isLive: Bool) {
self.timeline = timeline
self.isLive = isLive
}
func subscribeForUpdates() async {
guard innerTimelineProvider == nil else {
MXLog.warning("Timeline already subscribed for updates")
return
}
let paginationStatePublisher = backPaginationStatusSubject
.combineLatest(forwardPaginationStatusSubject)
.map { PaginationState(backward: $0.0, forward: $0.1) }
.eraseToAnyPublisher()
await subscribeToPagination()
let provider = await RoomTimelineProvider(timeline: timeline, isLive: isLive, paginationStatePublisher: paginationStatePublisher)
// Make sure the existing items are built so that we have content in the timeline before
// determining whether or not the timeline should paginate to load more items.
await provider.waitForInitialItems()
innerTimelineProvider = provider
}
func fetchDetails(for eventID: String) {
Task {
do {
MXLog.info("Fetching event details for \(eventID)")
try await self.timeline.fetchDetailsForEvent(eventId: eventID)
MXLog.info("Finished fetching event details for eventID: \(eventID)")
} catch {
MXLog.error("Failed fetching event details for eventID: \(eventID) with error: \(error)")
}
}
}
func messageEventContent(for timelineItemID: TimelineItemIdentifier) async -> RoomMessageEventContentWithoutRelation? {
await timelineProvider.itemProxies.firstEventTimelineItemUsingID(timelineItemID)?.content().asMessage()?.content()
}
func paginateBackwards(requestSize: UInt16) async -> Result<Void, TimelineProxyError> {
// We can't subscribe to back pagination on detached timelines and as live timelines
// can be shared between multiple instances of the same room on the stack, it is
// safer to still use the subscription logic for back pagination when live.
await if isLive {
paginateBackwardsOnLive(requestSize: requestSize)
} else {
focussedPaginate(.backwards, requestSize: requestSize)
}
}
func paginateForwards(requestSize: UInt16) async -> Result<Void, TimelineProxyError> {
await focussedPaginate(.forwards, requestSize: requestSize)
}
/// Paginate backwards using the subscription from Rust to drive the pagination state.
private func paginateBackwardsOnLive(requestSize: UInt16) async -> Result<Void, TimelineProxyError> {
MXLog.info("Paginating backwards")
do {
let _ = try await timeline.paginateBackwards(numEvents: requestSize)
MXLog.info("Finished paginating backwards")
return .success(())
} catch {
MXLog.error("Failed paginating backwards with error: \(error)")
return .failure(.sdkError(error))
}
}
/// Paginate forward or backwards using our own logic to drive the pagination state as the
/// Rust subscription isn't allowed on focussed/detached timelines.
private func focussedPaginate(_ direction: PaginationDirection, requestSize: UInt16) async -> Result<Void, TimelineProxyError> {
let subject = switch direction {
case .backwards: backPaginationStatusSubject
case .forwards: forwardPaginationStatusSubject
}
// This extra check is necessary as detached timelines don't support subscribing to pagination status.
// We need it to make sure we send a valid status after a failure.
guard subject.value == .idle else {
MXLog.error("Attempting to paginate \(direction.rawValue) when already at the end.")
return .failure(.failedPaginatingEndReached)
}
MXLog.info("Paginating \(direction.rawValue)")
subject.send(.paginating)
do {
let timelineEndReached = try await switch direction {
case .backwards: timeline.paginateBackwards(numEvents: requestSize)
case .forwards: timeline.focusedPaginateForwards(numEvents: requestSize)
}
MXLog.info("Finished paginating \(direction.rawValue)")
subject.send(timelineEndReached ? .timelineEndReached : .idle)
return .success(())
} catch {
MXLog.error("Failed paginating \(direction.rawValue) with error: \(error)")
subject.send(.idle)
return .failure(.sdkError(error))
}
}
func retryDecryption(for sessionID: String) async {
MXLog.info("Retrying decryption for sessionID: \(sessionID)")
await Task.dispatch(on: .global()) { [weak self] in
self?.timeline.retryDecryption(sessionIds: [sessionID])
MXLog.info("Finished retrying decryption for sessionID: \(sessionID)")
}
}
func edit(_ timelineItemID: TimelineItemIdentifier,
message: String, html: String?,
intentionalMentions: IntentionalMentions) async -> Result<Void, TimelineProxyError> {
MXLog.info("Editing timeline item: \(timelineItemID)")
let editMode: EditMode
if let eventID = timelineItemID.eventID {
editMode = .remote(eventID: eventID)
} else if let eventTimelineItem = await timelineProvider.itemProxies.firstEventTimelineItemUsingID(timelineItemID) {
editMode = .local(item: eventTimelineItem)
} else {
MXLog.error("Unknown timeline item: \(timelineItemID)")
return .failure(.failedEditing)
}
let messageContent = buildMessageContentFor(message,
html: html,
intentionalMentions: intentionalMentions.toRustMentions())
do {
switch editMode {
case let .local(item):
guard try await timeline.edit(item: item, newContent: messageContent) == true else {
return .failure(.failedEditing)
}
case let .remote(eventID):
try await timeline.editByEventId(eventId: eventID, newContent: messageContent)
}
MXLog.info("Finished editing timeline item: \(timelineItemID)")
return .success(())
} catch {
MXLog.error("Failed editing timeline item: \(timelineItemID) with error: \(error)")
return .failure(.sdkError(error))
}
}
func redact(_ timelineItemID: TimelineItemIdentifier, reason: String?) async -> Result<Void, TimelineProxyError> {
MXLog.info("Redacting timeline item: \(timelineItemID)")
guard let eventTimelineItem = await timelineProvider.itemProxies.firstEventTimelineItemUsingID(timelineItemID) else {
MXLog.error("Unknown timeline item: \(timelineItemID)")
return .failure(.failedRedacting)
}
do {
let success = try await timeline.redactEvent(item: eventTimelineItem, reason: reason)
guard success else {
MXLog.error("Failed redacting timeline item: \(timelineItemID)")
return .failure(.failedRedacting)
}
MXLog.info("Redacted timeline item: \(timelineItemID)")
return .success(())
} catch {
MXLog.error("Failed redacting timeline item: \(timelineItemID) with error: \(error)")
return .failure(.sdkError(error))
}
}
func getLoadedReplyDetails(eventID: String) async -> Result<InReplyToDetails, TimelineProxyError> {
do {
return try await .success(timeline.loadReplyDetails(eventIdStr: eventID))
} catch {
MXLog.error("Failed getting reply details for event \(eventID) with error: \(error)")
return .failure(.sdkError(error))
}
}
// MARK: - Sending
func sendAudio(url: URL,
audioInfo: AudioInfo,
progressSubject: CurrentValueSubject<Double, Never>?,
requestHandle: @MainActor (SendAttachmentJoinHandleProtocol) -> Void) async -> Result<Void, TimelineProxyError> {
MXLog.info("Sending audio")
let handle = timeline.sendAudio(url: url.path(percentEncoded: false), audioInfo: audioInfo, caption: nil, formattedCaption: nil, progressWatcher: UploadProgressListener { progress in
progressSubject?.send(progress)
})
await requestHandle(handle)
do {
try await handle.join()
MXLog.info("Finished sending audio")
} catch {
MXLog.error("Failed sending audio with error: \(error)")
return .failure(.sdkError(error))
}
return .success(())
}
func sendFile(url: URL,
fileInfo: FileInfo,
progressSubject: CurrentValueSubject<Double, Never>?,
requestHandle: @MainActor (SendAttachmentJoinHandleProtocol) -> Void) async -> Result<Void, TimelineProxyError> {
MXLog.info("Sending file")
let handle = timeline.sendFile(url: url.path(percentEncoded: false), fileInfo: fileInfo, progressWatcher: UploadProgressListener { progress in
progressSubject?.send(progress)
})
await requestHandle(handle)
do {
try await handle.join()
MXLog.info("Finished sending file")
} catch {
MXLog.error("Failed sending file with error: \(error)")
return .failure(.sdkError(error))
}
return .success(())
}
func sendImage(url: URL,
thumbnailURL: URL,
imageInfo: ImageInfo,
progressSubject: CurrentValueSubject<Double, Never>?,
requestHandle: @MainActor (SendAttachmentJoinHandleProtocol) -> Void) async -> Result<Void, TimelineProxyError> {
MXLog.info("Sending image")
let handle = timeline.sendImage(url: url.path(percentEncoded: false), thumbnailUrl: thumbnailURL.path(percentEncoded: false), imageInfo: imageInfo, caption: nil, formattedCaption: nil, progressWatcher: UploadProgressListener { progress in
progressSubject?.send(progress)
})
await requestHandle(handle)
do {
try await handle.join()
MXLog.info("Finished sending image")
} catch {
MXLog.error("Failed sending image with error: \(error)")
return .failure(.sdkError(error))
}
return .success(())
}
func sendLocation(body: String,
geoURI: GeoURI,
description: String?,
zoomLevel: UInt8?,
assetType: AssetType?) async -> Result<Void, TimelineProxyError> {
MXLog.info("Sending location")
await timeline.sendLocation(body: body,
geoUri: geoURI.string,
description: description,
zoomLevel: zoomLevel,
assetType: assetType)
MXLog.info("Finished sending location")
return .success(())
}
func sendVideo(url: URL,
thumbnailURL: URL,
videoInfo: VideoInfo,
progressSubject: CurrentValueSubject<Double, Never>?,
requestHandle: @MainActor (SendAttachmentJoinHandleProtocol) -> Void) async -> Result<Void, TimelineProxyError> {
MXLog.info("Sending video")
let handle = timeline.sendVideo(url: url.path(percentEncoded: false), thumbnailUrl: thumbnailURL.path(percentEncoded: false), videoInfo: videoInfo, caption: nil, formattedCaption: nil, progressWatcher: UploadProgressListener { progress in
progressSubject?.send(progress)
})
await requestHandle(handle)
do {
try await handle.join()
MXLog.info("Finished sending video")
} catch {
MXLog.error("Failed sending video with error: \(error)")
return .failure(.sdkError(error))
}
return .success(())
}
func sendVoiceMessage(url: URL,
audioInfo: AudioInfo,
waveform: [UInt16],
progressSubject: CurrentValueSubject<Double, Never>?,
requestHandle: @MainActor (SendAttachmentJoinHandleProtocol) -> Void) async -> Result<Void, TimelineProxyError> {
MXLog.info("Sending voice message")
let handle = timeline.sendVoiceMessage(url: url.path(percentEncoded: false), audioInfo: audioInfo, waveform: waveform, caption: nil, formattedCaption: nil, progressWatcher: UploadProgressListener { progress in
progressSubject?.send(progress)
})
await requestHandle(handle)
do {
try await handle.join()
MXLog.info("Finished sending voice message")
} catch {
MXLog.error("Failed sending vocie message with error: \(error)")
return .failure(.sdkError(error))
}
return .success(())
}
func sendMessage(_ message: String,
html: String?,
inReplyTo eventID: String? = nil,
intentionalMentions: IntentionalMentions) async -> Result<Void, TimelineProxyError> {
if let eventID {
MXLog.info("Sending reply to eventID: \(eventID)")
} else {
MXLog.info("Sending message")
}
let messageContent = buildMessageContentFor(message,
html: html,
intentionalMentions: intentionalMentions.toRustMentions())
do {
if let eventID {
try await timeline.sendReply(msg: messageContent, eventId: eventID)
MXLog.info("Finished sending reply to eventID: \(eventID)")
} else {
_ = try await timeline.send(msg: messageContent)
MXLog.info("Finished sending message")
}
} catch {
if let eventID {
MXLog.error("Failed sending reply to eventID: \(eventID) with error: \(error)")
} else {
MXLog.error("Failed sending message with error: \(error)")
}
return .failure(.sdkError(error))
}
return .success(())
}
func sendMessageEventContent(_ messageContent: RoomMessageEventContentWithoutRelation) async -> Result<Void, TimelineProxyError> {
MXLog.info("Sending message content")
do {
_ = try await timeline.send(msg: messageContent)
} catch {
MXLog.error("Failed sending message with error: \(error)")
}
MXLog.info("Finished sending message content")
return .success(())
}
func sendReadReceipt(for eventID: String, type: ReceiptType) async -> Result<Void, TimelineProxyError> {
MXLog.verbose("Sending read receipt for eventID: \(eventID)")
do {
try await timeline.sendReadReceipt(receiptType: type, eventId: eventID)
MXLog.info("Finished sending read receipt for eventID: \(eventID)")
return .success(())
} catch {
MXLog.error("Failed sending read receipt for eventID: \(eventID) with error: \(error)")
return .failure(.sdkError(error))
}
}
func toggleReaction(_ reaction: String, to eventID: String) async -> Result<Void, TimelineProxyError> {
MXLog.info("Toggling reaction for eventID: \(eventID)")
do {
try await timeline.toggleReaction(eventId: eventID, key: reaction)
MXLog.info("Finished toggling reaction for eventID: \(eventID)")
return .success(())
} catch {
MXLog.error("Failed toggling reaction for eventID: \(eventID)")
return .failure(.sdkError(error))
}
}
// MARK: - Polls
func createPoll(question: String, answers: [String], pollKind: Poll.Kind) async -> Result<Void, TimelineProxyError> {
MXLog.info("Creating poll")
do {
try await timeline.createPoll(question: question, answers: answers, maxSelections: 1, pollKind: .init(pollKind: pollKind))
MXLog.info("Finished creating poll")
return .success(())
} catch {
MXLog.error("Failed creating poll with error: \(error)")
return .failure(.sdkError(error))
}
}
func editPoll(original eventID: String,
question: String,
answers: [String],
pollKind: Poll.Kind) async -> Result<Void, TimelineProxyError> {
MXLog.info("Editing poll with eventID: \(eventID)")
do {
let originalEvent = try await timeline.getEventTimelineItemByEventId(eventId: eventID)
try await timeline.editPoll(question: question, answers: answers, maxSelections: 1, pollKind: .init(pollKind: pollKind), editItem: originalEvent)
MXLog.info("Finished editing poll with eventID: \(eventID)")
return .success(())
} catch {
MXLog.error("Failed editing poll with eventID: \(eventID) with error: \(error)")
return .failure(.sdkError(error))
}
}
func endPoll(pollStartID: String, text: String) async -> Result<Void, TimelineProxyError> {
MXLog.info("Ending poll with eventID: \(pollStartID)")
return await Task.dispatch(on: .global()) {
do {
try self.timeline.endPoll(pollStartId: pollStartID, text: text)
MXLog.info("Finished ending poll with eventID: \(pollStartID)")
return .success(())
} catch {
MXLog.error("Failed ending poll with eventID: \(pollStartID) with error: \(error)")
return .failure(.sdkError(error))
}
}
}
func sendPollResponse(pollStartID: String, answers: [String]) async -> Result<Void, TimelineProxyError> {
MXLog.info("Sending response for poll with eventID: \(pollStartID)")
do {
try await timeline.sendPollResponse(pollStartId: pollStartID, answers: answers)
MXLog.info("Finished sending response for poll with eventID: \(pollStartID)")
return .success(())
} catch {
MXLog.error("Failed sending response for poll with eventID: \(pollStartID) with error: \(error)")
return .failure(.sdkError(error))
}
}
// MARK: - Private
private func buildMessageContentFor(_ message: String,
html: String?,
intentionalMentions: Mentions) -> RoomMessageEventContentWithoutRelation {
let emoteSlashCommand = "/me "
let isEmote: Bool = message.starts(with: emoteSlashCommand)
let content: RoomMessageEventContentWithoutRelation
if isEmote {
let emoteMessage = String(message.dropFirst(emoteSlashCommand.count))
var emoteHtml: String?
if let html {
emoteHtml = String(html.dropFirst(emoteSlashCommand.count))
}
content = buildEmoteMessageContentFor(emoteMessage, html: emoteHtml)
} else {
if let html {
content = messageEventContentFromHtml(body: message, htmlBody: html)
} else {
content = messageEventContentFromMarkdown(md: message)
}
}
return content.withMentions(mentions: intentionalMentions)
}
private func buildEmoteMessageContentFor(_ message: String, html: String?) -> RoomMessageEventContentWithoutRelation {
if let html {
return messageEventContentFromHtmlAsEmote(body: message, htmlBody: html)
} else {
return messageEventContentFromMarkdownAsEmote(md: message)
}
}
private func subscribeToPagination() async {
if isLive {
let backPaginationListener = RoomPaginationStatusListener { [weak self] status in
guard let self else {
return
}
switch status {
case .idle(let hitStartOfTimeline):
backPaginationStatusSubject.send(hitStartOfTimeline ? .timelineEndReached : .idle)
case .paginating:
backPaginationStatusSubject.send(.paginating)
}
}
do {
backPaginationStatusObservationToken = try await timeline.subscribeToBackPaginationStatus(listener: backPaginationListener)
} catch {
MXLog.error("Failed to subscribe to back pagination status with error: \(error)")
}
} else {
// Detached timelines don't support observation, set the initial state ourself.
backPaginationStatusSubject.send(.idle)
}
// Detached timelines don't support observation, set the initial state ourself.
forwardPaginationStatusSubject.send(isLive ? .timelineEndReached : .idle)
}
}
private final class RoomPaginationStatusListener: PaginationStatusListener {
private let onUpdateClosure: (LiveBackPaginationStatus) -> Void
init(_ onUpdateClosure: @escaping (LiveBackPaginationStatus) -> Void) {
self.onUpdateClosure = onUpdateClosure
}
func onUpdate(status: LiveBackPaginationStatus) {
onUpdateClosure(status)
}
}
private final class UploadProgressListener: ProgressWatcher {
private let onUpdateClosure: (Double) -> Void
init(_ onUpdateClosure: @escaping (Double) -> Void) {
self.onUpdateClosure = onUpdateClosure
}
func transmissionProgress(progress: TransmissionProgress) {
DispatchQueue.main.async { [weak self] in
self?.onUpdateClosure(Double(progress.current) / Double(progress.total))
}
}
}
private extension MatrixRustSDK.PollKind {
init(pollKind: Poll.Kind) {
switch pollKind {
case .disclosed:
self = .disclosed
case .undisclosed:
self = .undisclosed
}
}
}
extension Array where Element == TimelineItemProxy {
func firstEventTimelineItemUsingID(_ id: TimelineItemIdentifier) -> EventTimelineItem? {
var eventTimelineItemProxy: EventTimelineItemProxy?
for item in self {
if case let .event(eventTimelineItem) = item {
if eventTimelineItem.id == id {
eventTimelineItemProxy = eventTimelineItem
break
}
}
}
return eventTimelineItemProxy?.item
}
}
private enum EditMode {
/// edit for a message that is also found locally as a timeline item
case local(item: EventTimelineItem)
/// edit for a message that was not found locally
case remote(eventID: String)
}