-
Notifications
You must be signed in to change notification settings - Fork 397
Expand file tree
/
Copy pathclient.rs
More file actions
3060 lines (2724 loc) · 113 KB
/
client.rs
File metadata and controls
3060 lines (2724 loc) · 113 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
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2025 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 that specific language governing permissions and
// limitations under the License.
use std::{
collections::HashMap,
fmt::Debug,
path::PathBuf,
sync::{Arc, OnceLock},
time::Duration,
};
use anyhow::{anyhow, Context as _};
use futures_util::pin_mut;
#[cfg(not(target_family = "wasm"))]
use matrix_sdk::media::MediaFileHandle as SdkMediaFileHandle;
#[cfg(feature = "sqlite")]
use matrix_sdk::STATE_STORE_DATABASE_NAME;
use matrix_sdk::{
authentication::oauth::{ClientId, OAuthAuthorizationData, OAuthError, OAuthSession},
deserialized_responses::RawAnySyncOrStrippedTimelineEvent,
executor::AbortOnDrop,
media::{MediaFormat, MediaRequestParameters, MediaRetentionPolicy, MediaThumbnailSettings},
ruma::{
api::client::{
discovery::{
discover_homeserver::RtcFocusInfo,
get_authorization_server_metadata::v1::Prompt as RumaOidcPrompt,
},
push::{EmailPusherData, PusherIds, PusherInit, PusherKind as RumaPusherKind},
room::{create_room, Visibility},
session::get_login_types,
user_directory::search_users,
},
events::{
room::{
avatar::RoomAvatarEventContent, encryption::RoomEncryptionEventContent,
message::MessageType,
},
AnyInitialStateEvent, InitialStateEvent,
},
serde::Raw,
EventEncryptionAlgorithm, RoomId, TransactionId, UInt, UserId,
},
sliding_sync::Version as SdkSlidingSyncVersion,
store::RoomLoadSettings as SdkRoomLoadSettings,
task_monitor::BackgroundTaskFailureReason,
Account, AuthApi, AuthSession, Client as MatrixClient, Error, SessionChange, SessionTokens,
};
use matrix_sdk_common::{
cross_process_lock::CrossProcessLockConfig, stream::StreamExt, SendOutsideWasm, SyncOutsideWasm,
};
use matrix_sdk_ui::{
notification_client::{
NotificationClient as MatrixNotificationClient,
NotificationProcessSetup as MatrixNotificationProcessSetup,
},
spaces::SpaceService as UISpaceService,
unable_to_decrypt_hook::UtdHookManager,
};
use mime::Mime;
use oauth2::Scope;
use ruma::{
api::client::{
alias::get_alias,
discovery::get_authorization_server_metadata::v1::{
AccountManagementActionData, DeviceDeleteData, DeviceViewData,
},
error::ErrorKind,
profile::{AvatarUrl, DisplayName},
room::create_room::{v3::CreationContent, RoomPowerLevelsContentOverride},
uiaa::UserIdentifier,
},
events::{
direct::DirectEventContent,
fully_read::FullyReadEventContent,
identity_server::IdentityServerEventContent,
ignored_user_list::IgnoredUserListEventContent,
key::verification::request::ToDeviceKeyVerificationRequestEvent,
marked_unread::{MarkedUnreadEventContent, UnstableMarkedUnreadEventContent},
push_rules::PushRulesEventContent,
room::{
history_visibility::RoomHistoryVisibilityEventContent,
join_rules::{
AllowRule as RumaAllowRule, JoinRule as RumaJoinRule, RoomJoinRulesEventContent,
},
message::{OriginalSyncRoomMessageEvent, Relation},
},
secret_storage::{
default_key::SecretStorageDefaultKeyEventContent, key::SecretStorageKeyEventContent,
},
tag::TagEventContent,
AnyMessageLikeEventContent, AnySyncTimelineEvent,
GlobalAccountDataEvent as RumaGlobalAccountDataEvent,
RoomAccountDataEvent as RumaRoomAccountDataEvent,
},
push::{HttpPusherData as RumaHttpPusherData, PushFormat as RumaPushFormat},
room::RoomType,
OwnedDeviceId, OwnedServerName, RoomAliasId, RoomOrAliasId, ServerName,
};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tokio::sync::broadcast::error::RecvError;
use tracing::{debug, error};
use url::Url;
use super::{
room::{room_info::RoomInfo, Room},
session_verification::SessionVerificationController,
};
use crate::{
authentication::{HomeserverLoginDetails, OidcConfiguration, OidcError, SsoError, SsoHandler},
client,
encryption::Encryption,
notification::{
NotificationClient, NotificationEvent, NotificationItem, NotificationRoomInfo,
NotificationSenderInfo,
},
notification_settings::NotificationSettings,
qr_code::{GrantLoginWithQrCodeHandler, LoginWithQrCodeHandler},
room::{RoomHistoryVisibility, RoomInfoListener, RoomSendQueueUpdate},
room_directory_search::RoomDirectorySearch,
room_preview::RoomPreview,
ruma::{
AccountDataEvent, AccountDataEventType, AuthData, InviteAvatars, MediaPreviewConfig,
MediaPreviews, MediaSource, RoomAccountDataEvent, RoomAccountDataEventType,
},
runtime::get_runtime_handle,
spaces::SpaceService,
sync_service::{SyncService, SyncServiceBuilder},
task_handle::TaskHandle,
utd::{UnableToDecryptDelegate, UtdHook},
utils::AsyncRuntimeDropped,
ClientError,
};
#[derive(Clone, uniffi::Record)]
pub struct PusherIdentifiers {
pub pushkey: String,
pub app_id: String,
}
impl From<PusherIdentifiers> for PusherIds {
fn from(value: PusherIdentifiers) -> Self {
Self::new(value.pushkey, value.app_id)
}
}
#[derive(Clone, uniffi::Record)]
pub struct HttpPusherData {
pub url: String,
pub format: Option<PushFormat>,
pub default_payload: Option<String>,
}
#[derive(Clone, uniffi::Enum)]
pub enum PusherKind {
Http { data: HttpPusherData },
Email,
}
impl TryFrom<PusherKind> for RumaPusherKind {
type Error = anyhow::Error;
fn try_from(value: PusherKind) -> anyhow::Result<Self> {
match value {
PusherKind::Http { data } => {
let mut ruma_data = RumaHttpPusherData::new(data.url);
if let Some(payload) = data.default_payload {
let json: Value = serde_json::from_str(&payload)?;
ruma_data.data.insert("default_payload".to_owned(), json);
}
ruma_data.format = data.format.map(Into::into);
Ok(Self::Http(ruma_data))
}
PusherKind::Email => {
let ruma_data = EmailPusherData::new();
Ok(Self::Email(ruma_data))
}
}
}
}
#[derive(Clone, uniffi::Enum)]
pub enum PushFormat {
EventIdOnly,
}
impl From<PushFormat> for RumaPushFormat {
fn from(value: PushFormat) -> Self {
match value {
client::PushFormat::EventIdOnly => Self::EventIdOnly,
}
}
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait ClientDelegate: SyncOutsideWasm + SendOutsideWasm {
/// A callback invoked whenever the SDK runs into an unknown token error.
fn did_receive_auth_error(&self, is_soft_logout: bool);
/// A callback invoked when a background task registered with the client's
/// task monitor encounters an error.
///
/// Can default to an empty implementation, if the embedder doesn't care
/// about handling background jobs errors.
fn on_background_task_error_report(
&self,
task_name: String,
error: BackgroundTaskFailureReason,
);
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait ClientSessionDelegate: SyncOutsideWasm + SendOutsideWasm {
fn retrieve_session_from_keychain(&self, user_id: String) -> Result<Session, ClientError>;
fn save_session_in_keychain(&self, session: Session);
}
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait ProgressWatcher: SyncOutsideWasm + SendOutsideWasm {
fn transmission_progress(&self, progress: TransmissionProgress);
}
/// A listener to the global (client-wide) update reporter of the send queue.
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait SendQueueRoomUpdateListener: SyncOutsideWasm + SendOutsideWasm {
/// Called every time the send queue emits an update for a given room.
fn on_update(&self, room_id: String, update: RoomSendQueueUpdate);
}
/// A listener to the global (client-wide) error reporter of the send queue.
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait SendQueueRoomErrorListener: SyncOutsideWasm + SendOutsideWasm {
/// Called every time the send queue has ran into an error for a given room,
/// which will disable the send queue for that particular room.
fn on_error(&self, room_id: String, error: ClientError);
}
/// A listener for changes of global account data events.
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait AccountDataListener: SyncOutsideWasm + SendOutsideWasm {
/// Called when a global account data event has changed.
fn on_change(&self, event: AccountDataEvent);
}
/// A listener for duplicate key upload errors triggered by requests to
/// /keys/upload.
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait DuplicateKeyUploadErrorListener: SyncOutsideWasm + SendOutsideWasm {
/// Called once when uploading keys fails.
fn on_duplicate_key_upload_error(&self, message: Option<DuplicateOneTimeKeyErrorMessage>);
}
/// Information about the old and new key that caused a duplicate key upload
/// error in /keys/upload.
#[derive(uniffi::Record)]
pub struct DuplicateOneTimeKeyErrorMessage {
/// The previously uploaded one-time key, encoded as unpadded base64.
pub old_key: String,
/// The one-time key we attempted to upload, encoded as unpadded base64
pub new_key: String,
}
impl From<matrix_sdk::encryption::DuplicateOneTimeKeyErrorMessage>
for DuplicateOneTimeKeyErrorMessage
{
fn from(value: matrix_sdk::encryption::DuplicateOneTimeKeyErrorMessage) -> Self {
Self { old_key: value.old_key.to_base64(), new_key: value.new_key.to_base64() }
}
}
/// A listener for changes of room account data events.
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait RoomAccountDataListener: SyncOutsideWasm + SendOutsideWasm {
/// Called when a room account data event was changed.
fn on_change(&self, event: RoomAccountDataEvent, room_id: String);
}
/// A listener for notifications generated from sync responses.
///
/// This is called during sync for each event that triggers a notification
/// based on the user's push rules.
#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait SyncNotificationListener: SyncOutsideWasm + SendOutsideWasm {
/// Called when a notifying event is received during sync.
fn on_notification(&self, notification: NotificationItem, room_id: String);
}
#[derive(Clone, Copy, uniffi::Record)]
pub struct TransmissionProgress {
pub current: u64,
pub total: u64,
}
impl From<matrix_sdk::TransmissionProgress> for TransmissionProgress {
fn from(value: matrix_sdk::TransmissionProgress) -> Self {
Self {
current: value.current.try_into().unwrap_or(u64::MAX),
total: value.total.try_into().unwrap_or(u64::MAX),
}
}
}
struct ClientDelegateData {
/// The delegate itself, that will receive the callbacks.
delegate: Arc<dyn ClientDelegate>,
// The background task error listener task, that will forward errors occurring in background
// jobs to the delegate.
_background_error_listener_task: Arc<AbortOnDrop<()>>,
}
#[derive(uniffi::Object)]
pub struct Client {
pub(crate) inner: AsyncRuntimeDropped<MatrixClient>,
delegate_data: OnceLock<ClientDelegateData>,
pub(crate) utd_hook_manager: OnceLock<Arc<UtdHookManager>>,
session_verification_controller:
Arc<tokio::sync::RwLock<Option<SessionVerificationController>>>,
/// The path to the directory where the state store and the crypto store are
/// located, if the `Client` instance has been built with a store (either
/// SQLite or IndexedDB).
#[cfg_attr(not(feature = "sqlite"), allow(unused))]
store_path: Option<PathBuf>,
}
impl Client {
pub async fn new(
sdk_client: MatrixClient,
session_delegate: Option<Arc<dyn ClientSessionDelegate>>,
store_path: Option<PathBuf>,
) -> Result<Self, ClientError> {
let session_verification_controller: Arc<
tokio::sync::RwLock<Option<SessionVerificationController>>,
> = Default::default();
let controller = session_verification_controller.clone();
sdk_client.add_event_handler(
move |event: ToDeviceKeyVerificationRequestEvent| async move {
if let Some(session_verification_controller) = &*controller.clone().read().await {
session_verification_controller
.process_incoming_verification_request(
&event.sender,
event.content.transaction_id,
)
.await;
}
},
);
let controller = session_verification_controller.clone();
sdk_client.add_event_handler(move |event: OriginalSyncRoomMessageEvent| async move {
if let MessageType::VerificationRequest(_) = &event.content.msgtype {
if let Some(session_verification_controller) = &*controller.clone().read().await {
session_verification_controller
.process_incoming_verification_request(&event.sender, event.event_id)
.await;
}
}
});
let store_mode = sdk_client.cross_process_lock_config();
let client = Client {
inner: AsyncRuntimeDropped::new(sdk_client.clone()),
delegate_data: OnceLock::new(),
utd_hook_manager: OnceLock::new(),
session_verification_controller,
store_path,
};
match store_mode {
CrossProcessLockConfig::MultiProcess { holder_name } => {
if session_delegate.is_none() {
return Err(anyhow::anyhow!(
"missing session delegates with multi-process lock configuration"
))?;
}
client.inner.oauth().enable_cross_process_refresh_lock(holder_name.clone()).await?;
}
CrossProcessLockConfig::SingleProcess => {
client.inner.oauth();
}
}
if let Some(session_delegate) = session_delegate {
client.inner.set_session_callbacks(
{
let session_delegate = session_delegate.clone();
Box::new(move |client| {
let session_delegate = session_delegate.clone();
let user_id = client.user_id().context("user isn't logged in")?;
Ok(Self::retrieve_session(session_delegate, user_id)?)
})
},
{
let session_delegate = session_delegate.clone();
Box::new(move |client| {
let session_delegate = session_delegate.clone();
Ok(Self::save_session(session_delegate, client)?)
})
},
)?;
}
Ok(client)
}
}
#[matrix_sdk_ffi_macros::export]
impl Client {
/// Perform database optimizations if any are available, i.e. vacuuming in
/// SQLite.
pub async fn optimize_stores(&self) -> Result<(), ClientError> {
Ok(self.inner.optimize_stores().await?)
}
/// Returns the sizes of the existing stores, if known.
pub async fn get_store_sizes(&self) -> Result<StoreSizes, ClientError> {
Ok(self.inner.get_store_sizes().await?.into())
}
/// Information about login options for the client's homeserver.
pub async fn homeserver_login_details(&self) -> Arc<HomeserverLoginDetails> {
let oauth = self.inner.oauth();
let (supports_oidc_login, supported_oidc_prompts) = match oauth.server_metadata().await {
Ok(metadata) => {
let prompts =
metadata.prompt_values_supported.into_iter().map(Into::into).collect();
(true, prompts)
}
Err(error) => {
error!("Failed to fetch OIDC provider metadata: {error}");
(false, Default::default())
}
};
let login_types = self.inner.matrix_auth().get_login_types().await.ok();
let supports_password_login = login_types
.as_ref()
.map(|login_types| {
login_types.flows.iter().any(|login_type| {
matches!(login_type, get_login_types::v3::LoginType::Password(_))
})
})
.unwrap_or(false);
let supports_sso_login = login_types
.as_ref()
.map(|login_types| {
login_types
.flows
.iter()
.any(|login_type| matches!(login_type, get_login_types::v3::LoginType::Sso(_)))
})
.unwrap_or(false);
let sliding_sync_version = self.sliding_sync_version();
Arc::new(HomeserverLoginDetails {
url: self.homeserver(),
sliding_sync_version,
supports_oidc_login,
supported_oidc_prompts,
supports_sso_login,
supports_password_login,
})
}
/// Login using a username and password.
pub async fn login(
&self,
username: String,
password: String,
initial_device_name: Option<String>,
device_id: Option<String>,
) -> Result<(), ClientError> {
let mut builder = self.inner.matrix_auth().login_username(&username, &password);
if let Some(initial_device_name) = initial_device_name.as_ref() {
builder = builder.initial_device_display_name(initial_device_name);
}
if let Some(device_id) = device_id.as_ref() {
builder = builder.device_id(device_id);
}
builder.send().await?;
Ok(())
}
/// Login using JWT
/// This is an implementation of the custom_login https://docs.rs/matrix-sdk/latest/matrix_sdk/matrix_auth/struct.MatrixAuth.html#method.login_custom
/// For more information on logging in with JWT: https://element-hq.github.io/synapse/latest/jwt.html
pub async fn custom_login_with_jwt(
&self,
jwt: String,
initial_device_name: Option<String>,
device_id: Option<String>,
) -> Result<(), ClientError> {
let data = json!({ "token": jwt }).as_object().unwrap().clone();
let mut builder = self.inner.matrix_auth().login_custom("org.matrix.login.jwt", data)?;
if let Some(initial_device_name) = initial_device_name.as_ref() {
builder = builder.initial_device_display_name(initial_device_name);
}
if let Some(device_id) = device_id.as_ref() {
builder = builder.device_id(device_id);
}
builder.send().await?;
Ok(())
}
/// Login using an email and password.
pub async fn login_with_email(
&self,
email: String,
password: String,
initial_device_name: Option<String>,
device_id: Option<String>,
) -> Result<(), ClientError> {
let mut builder = self
.inner
.matrix_auth()
.login_identifier(UserIdentifier::Email { address: email }, &password);
if let Some(initial_device_name) = initial_device_name.as_ref() {
builder = builder.initial_device_display_name(initial_device_name);
}
if let Some(device_id) = device_id.as_ref() {
builder = builder.device_id(device_id);
}
builder.send().await?;
Ok(())
}
/// Returns a handler to start the SSO login process.
pub(crate) async fn start_sso_login(
self: &Arc<Self>,
redirect_url: String,
idp_id: Option<String>,
) -> Result<Arc<SsoHandler>, SsoError> {
let auth = self.inner.matrix_auth();
let url = auth
.get_sso_login_url(redirect_url.as_str(), idp_id.as_deref())
.await
.map_err(|e| SsoError::Generic { message: e.to_string() })?;
Ok(Arc::new(SsoHandler { client: Arc::clone(self), url }))
}
/// Requests the URL needed for opening a web view using OIDC. Once the web
/// view has succeeded, call `login_with_oidc_callback` with the callback it
/// returns. If a failure occurs and a callback isn't available, make sure
/// to call `abort_oidc_auth` to inform the client of this.
///
/// # Arguments
///
/// * `oidc_configuration` - The configuration used to load the credentials
/// of the client if it is already registered with the authorization
/// server, or register the client and store its credentials if it isn't.
///
/// * `prompt` - The desired user experience in the web UI. No value means
/// that the user wishes to login into an existing account, and a value of
/// `Create` means that the user wishes to register a new account.
///
/// * `login_hint` - A generic login hint that an identity provider can use
/// to pre-fill the login form. The format of this hint is not restricted
/// by the spec as external providers all have their own way to handle the hint.
/// However, it should be noted that when providing a user ID as a hint
/// for MAS (with no upstream provider), then the format to use is defined
/// by [MSC4198]: https://github.com/matrix-org/matrix-spec-proposals/pull/4198
///
/// * `device_id` - The unique ID that will be associated with the session.
/// If not set, a random one will be generated. It can be an existing
/// device ID from a previous login call. Note that this should be done
/// only if the client also holds the corresponding encryption keys.
///
/// * `additional_scopes` - Additional scopes to request from the
/// authorization server, e.g. "urn:matrix:client:com.example.msc9999.foo".
/// The scopes for API access and the device ID according to the
/// [specification](https://spec.matrix.org/v1.15/client-server-api/#allocated-scope-tokens)
/// are always requested.
pub async fn url_for_oidc(
&self,
oidc_configuration: &OidcConfiguration,
prompt: Option<OidcPrompt>,
login_hint: Option<String>,
device_id: Option<String>,
additional_scopes: Option<Vec<String>>,
) -> Result<Arc<OAuthAuthorizationData>, OidcError> {
let registration_data = oidc_configuration.registration_data()?;
let redirect_uri = oidc_configuration.redirect_uri()?;
let device_id = device_id.map(OwnedDeviceId::from);
let additional_scopes =
additional_scopes.map(|scopes| scopes.into_iter().map(Scope::new).collect::<Vec<_>>());
let mut url_builder = self.inner.oauth().login(
redirect_uri,
device_id,
Some(registration_data),
additional_scopes,
);
if let Some(prompt) = prompt {
url_builder = url_builder.prompt(vec![prompt.into()]);
}
if let Some(login_hint) = login_hint {
url_builder = url_builder.login_hint(login_hint);
}
let data = url_builder.build().await?;
Ok(Arc::new(data))
}
/// Aborts an existing OIDC login operation that might have been cancelled,
/// failed etc.
pub async fn abort_oidc_auth(&self, authorization_data: Arc<OAuthAuthorizationData>) {
self.inner.oauth().abort_login(&authorization_data.state).await;
}
/// Completes the OIDC login process.
pub async fn login_with_oidc_callback(&self, callback_url: String) -> Result<(), OidcError> {
let url = Url::parse(&callback_url).or(Err(OidcError::CallbackUrlInvalid))?;
self.inner.oauth().finish_login(url.into()).await?;
Ok(())
}
/// Create a handler for requesting an existing device to grant login to
/// this device by way of a QR code.
///
/// # Arguments
///
/// * `oidc_configuration` - The data to restore or register the client with
/// the server.
pub fn new_login_with_qr_code_handler(
self: Arc<Self>,
oidc_configuration: OidcConfiguration,
) -> LoginWithQrCodeHandler {
LoginWithQrCodeHandler::new(self.inner.oauth(), oidc_configuration)
}
/// Create a handler for granting login from this device to a new device by
/// way of a QR code.
pub fn new_grant_login_with_qr_code_handler(self: Arc<Self>) -> GrantLoginWithQrCodeHandler {
GrantLoginWithQrCodeHandler::new(self.inner.oauth())
}
/// Restores the client from a `Session`.
///
/// It reloads the entire set of rooms from the previous session.
///
/// If you want to control the amount of rooms to reloads, check
/// [`Client::restore_session_with`].
pub async fn restore_session(&self, session: Session) -> Result<(), ClientError> {
self.restore_session_with(session, RoomLoadSettings::All).await
}
/// Restores the client from a `Session`.
///
/// It reloads a set of rooms controlled by [`RoomLoadSettings`].
pub async fn restore_session_with(
&self,
session: Session,
room_load_settings: RoomLoadSettings,
) -> Result<(), ClientError> {
let sliding_sync_version = session.sliding_sync_version.clone();
let auth_session: AuthSession = session.try_into()?;
self.inner
.restore_session_with(
auth_session,
room_load_settings
.try_into()
.map_err(|error| ClientError::from_str(error, None))?,
)
.await?;
self.inner.set_sliding_sync_version(sliding_sync_version.try_into()?);
Ok(())
}
/// Enables or disables all the room send queues at once.
///
/// When connectivity is lost on a device, it is recommended to disable the
/// room sending queues.
///
/// This can be controlled for individual rooms, using
/// [`Room::enable_send_queue`].
pub async fn enable_all_send_queues(&self, enable: bool) {
self.inner.send_queue().set_enabled(enable).await;
}
/// Enables or disables progress reporting for media uploads in the send
/// queue.
pub fn enable_send_queue_upload_progress(&self, enable: bool) {
self.inner.send_queue().enable_upload_progress(enable);
}
/// Subscribe to the global send queue update reporter, at the
/// client-wide level.
///
/// The given listener will be immediately called with
/// `RoomSendQueueUpdate::NewLocalEvent` for each local echo existing in
/// the queue.
pub async fn subscribe_to_send_queue_updates(
&self,
listener: Box<dyn SendQueueRoomUpdateListener>,
) -> Result<Arc<TaskHandle>, ClientError> {
let q = self.inner.send_queue();
let local_echoes = q.local_echoes().await?;
let mut subscriber = q.subscribe();
for (room_id, local_echoes) in local_echoes {
for local_echo in local_echoes {
listener.on_update(
room_id.clone().into(),
RoomSendQueueUpdate::NewLocalEvent {
transaction_id: local_echo.transaction_id.into(),
},
);
}
}
Ok(Arc::new(TaskHandle::new(get_runtime_handle().spawn(async move {
loop {
match subscriber.recv().await {
Ok(update) => {
let room_id = update.room_id.to_string();
match update.update.try_into() {
Ok(update) => listener.on_update(room_id, update),
Err(err) => error!("error when converting send queue update: {err}"),
}
}
Err(err) => {
error!("error when listening to the send queue update reporter: {err}");
}
}
}
}))))
}
/// Subscribe to the global enablement status of the send queue, at the
/// client-wide level.
///
/// The given listener will be immediately called with the initial value of
/// the enablement status.
pub fn subscribe_to_send_queue_status(
&self,
listener: Box<dyn SendQueueRoomErrorListener>,
) -> Arc<TaskHandle> {
let q = self.inner.send_queue();
let mut subscriber = q.subscribe_errors();
Arc::new(TaskHandle::new(get_runtime_handle().spawn(async move {
// Respawn tasks for rooms that had unsent events. At this point we've just
// created the subscriber, so it'll be notified about errors.
q.respawn_tasks_for_rooms_with_unsent_requests().await;
loop {
match subscriber.recv().await {
Ok(report) => listener
.on_error(report.room_id.to_string(), ClientError::from_err(report.error)),
Err(err) => {
error!("error when listening to the send queue error reporter: {err}");
}
}
}
})))
}
/// Subscribe to duplicate key upload errors triggered by requests to
/// /keys/upload.
pub fn subscribe_to_duplicate_key_upload_errors(
&self,
listener: Box<dyn DuplicateKeyUploadErrorListener>,
) -> Arc<TaskHandle> {
let mut subscriber = self.inner.subscribe_to_duplicate_key_upload_errors();
Arc::new(TaskHandle::new(get_runtime_handle().spawn(async move {
loop {
match subscriber.recv().await {
Ok(message) => {
listener.on_duplicate_key_upload_error(message.map(|m| m.into()))
}
Err(err) => {
error!("error when listening to key upload errors: {err}");
}
}
}
})))
}
/// Subscribe to updates of global account data events.
///
/// Be careful that only the most recent value can be observed. Subscribers
/// are notified when a new value is sent, but there is no guarantee that
/// they will see all values.
pub fn observe_account_data_event(
&self,
event_type: AccountDataEventType,
listener: Box<dyn AccountDataListener>,
) -> Arc<TaskHandle> {
macro_rules! observe {
($t:ty, $cb: expr) => {{
// Using an Arc here is mandatory or else the subscriber will never trigger
let observer =
Arc::new(self.inner.observe_events::<RumaGlobalAccountDataEvent<$t>, ()>());
Arc::new(TaskHandle::new(get_runtime_handle().spawn(async move {
let mut subscriber = observer.subscribe();
loop {
if let Some(next) = subscriber.next().await {
$cb(next.0);
}
}
})))
}};
($t:ty) => {{
observe!($t, |event: RumaGlobalAccountDataEvent<$t>| {
listener.on_change(event.into());
})
}};
}
match event_type {
AccountDataEventType::Direct => {
observe!(DirectEventContent)
}
AccountDataEventType::IdentityServer => {
observe!(IdentityServerEventContent)
}
AccountDataEventType::IgnoredUserList => {
observe!(IgnoredUserListEventContent)
}
AccountDataEventType::PushRules => {
observe!(PushRulesEventContent, |event: RumaGlobalAccountDataEvent<
PushRulesEventContent,
>| {
if let Ok(event) = event.try_into() {
listener.on_change(event);
}
})
}
AccountDataEventType::SecretStorageDefaultKey => {
observe!(SecretStorageDefaultKeyEventContent)
}
AccountDataEventType::SecretStorageKey { key_id } => {
observe!(SecretStorageKeyEventContent, |event: RumaGlobalAccountDataEvent<
SecretStorageKeyEventContent,
>| {
if event.content.key_id != key_id {
return;
}
if let Ok(event) = event.try_into() {
listener.on_change(event);
}
})
}
}
}
/// Subscribe to updates of room account data events.
///
/// Be careful that only the most recent value can be observed. Subscribers
/// are notified when a new value is sent, but there is no guarantee that
/// they will see all values.
pub fn observe_room_account_data_event(
&self,
room_id: String,
event_type: RoomAccountDataEventType,
listener: Box<dyn RoomAccountDataListener>,
) -> Result<Arc<TaskHandle>, ClientError> {
macro_rules! observe {
($t:ty, $cb: expr) => {{
// Using an Arc here is mandatory or else the subscriber will never trigger
let observer =
Arc::new(self.inner.observe_room_events::<RumaRoomAccountDataEvent<$t>, ()>(
&RoomId::parse(&room_id)?,
));
Ok(Arc::new(TaskHandle::new(get_runtime_handle().spawn(async move {
let mut subscriber = observer.subscribe();
loop {
if let Some(next) = subscriber.next().await {
$cb(next.0);
}
}
}))))
}};
($t:ty) => {{
observe!($t, |event: RumaRoomAccountDataEvent<$t>| {
listener.on_change(event.into(), room_id.clone());
})
}};
}
match event_type {
RoomAccountDataEventType::FullyRead => {
observe!(FullyReadEventContent)
}
RoomAccountDataEventType::MarkedUnread => {
observe!(MarkedUnreadEventContent)
}
RoomAccountDataEventType::Tag => {
observe!(TagEventContent, |event: RumaRoomAccountDataEvent<TagEventContent>| {
if let Ok(event) = event.try_into() {
listener.on_change(event, room_id.clone());
}
})
}
RoomAccountDataEventType::UnstableMarkedUnread => {
observe!(UnstableMarkedUnreadEventContent)
}
}
}
/// Register a handler for notifications generated from sync responses.
///
/// The handler will be called during sync for each event that triggers
/// a notification based on the user's push rules.
///
/// The handler receives:
/// - The notification with push actions and event data
/// - The room ID where the notification occurred
///
/// This is useful for implementing custom notification logic, such as
/// displaying local notifications or updating notification badges.
pub async fn register_notification_handler(&self, listener: Box<dyn SyncNotificationListener>) {
let listener = Arc::new(listener);
self.inner
.register_notification_handler(move |notification, room, _client| {
let listener = listener.clone();
let room_id = room.room_id().to_string();
async move {
// Extract information about the actions
let is_noisy = notification.actions.iter().any(|a| a.sound().is_some());
let has_mention = notification.actions.iter().any(|a| a.is_highlight());
// Convert SDK actions to FFI type
let actions: Vec<crate::notification_settings::Action> = notification
.actions
.into_iter()
.filter_map(|action| action.try_into().ok())
.collect();
// Convert SDK event to FFI type
let (sender, event, thread_id, raw_event) = match notification.event {
RawAnySyncOrStrippedTimelineEvent::Sync(raw) => {
let raw_event = raw.json().get().to_owned();
match raw.deserialize() {
Ok(deserialized) => {
let sender = deserialized.sender().to_owned();
let thread_id = match &deserialized {
AnySyncTimelineEvent::MessageLike(event) => {
match event.original_content() {
Some(AnyMessageLikeEventContent::RoomMessage(
content,
)) => match content.relates_to {
Some(Relation::Thread(thread)) => {
Some(thread.event_id.to_string())
}
_ => None,
},
_ => None,
}
}
_ => None,
};
let event = NotificationEvent::Timeline {
event: Arc::new(crate::event::TimelineEvent(Box::new(
deserialized,