-
Notifications
You must be signed in to change notification settings - Fork 253
/
mod.rs
2914 lines (2626 loc) · 106 KB
/
mod.rs
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 2020 Damir Jelić
// Copyright 2020 The Matrix.org Foundation C.I.C.
// Copyright 2022 Famedly GmbH
//
// 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.
use std::{
collections::{btree_map, BTreeMap},
fmt::{self, Debug},
future::Future,
pin::Pin,
sync::{Arc, Mutex as StdMutex, RwLock as StdRwLock, Weak},
};
use eyeball::{SharedObservable, Subscriber};
#[cfg(not(target_arch = "wasm32"))]
use eyeball_im::VectorDiff;
use futures_core::Stream;
#[cfg(not(target_arch = "wasm32"))]
use futures_util::StreamExt;
#[cfg(not(target_arch = "wasm32"))]
use imbl::Vector;
#[cfg(feature = "e2e-encryption")]
use matrix_sdk_base::crypto::store::LockableCryptoStore;
use matrix_sdk_base::{
event_cache_store::DynEventCacheStore,
store::{DynStateStore, ServerCapabilities},
sync::{Notification, RoomUpdates},
BaseClient, RoomInfoNotableUpdate, RoomState, RoomStateFilter, SendOutsideWasm, SessionMeta,
StateStoreDataKey, StateStoreDataValue, SyncOutsideWasm,
};
#[cfg(feature = "e2e-encryption")]
use ruma::events::{room::encryption::RoomEncryptionEventContent, InitialStateEvent};
use ruma::{
api::{
client::{
account::whoami,
alias::get_alias,
device::{delete_devices, get_devices, update_device},
directory::{get_public_rooms, get_public_rooms_filtered},
discovery::{
get_capabilities::{self, Capabilities},
get_supported_versions,
},
filter::{create_filter::v3::Request as FilterUploadRequest, FilterDefinition},
membership::{join_room_by_id, join_room_by_id_or_alias},
room::create_room,
session::login::v3::DiscoveryInfo,
sync::sync_events,
uiaa,
user_directory::search_users,
},
error::FromHttpResponseError,
MatrixVersion, OutgoingRequest,
},
assign,
push::Ruleset,
time::Instant,
DeviceId, OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedServerName, RoomAliasId, RoomId,
RoomOrAliasId, ServerName, UInt, UserId,
};
use serde::de::DeserializeOwned;
use tokio::sync::{broadcast, Mutex, OnceCell, RwLock, RwLockReadGuard};
use tracing::{debug, error, instrument, trace, warn, Instrument, Span};
use url::Url;
use self::futures::SendRequest;
#[cfg(feature = "experimental-oidc")]
use crate::oidc::Oidc;
#[cfg(feature = "experimental-sliding-sync")]
use crate::sliding_sync::Version as SlidingSyncVersion;
use crate::{
authentication::{AuthCtx, AuthData, ReloadSessionCallback, SaveSessionCallback},
config::RequestConfig,
deduplicating_handler::DeduplicatingHandler,
error::{HttpError, HttpResult},
event_cache::EventCache,
event_handler::{
EventHandler, EventHandlerDropGuard, EventHandlerHandle, EventHandlerStore, SyncEvent,
},
http_client::HttpClient,
matrix_auth::MatrixAuth,
notification_settings::NotificationSettings,
room_preview::RoomPreview,
send_queue::SendQueueData,
sync::{RoomUpdate, SyncResponse},
Account, AuthApi, AuthSession, Error, Media, Pusher, RefreshTokenError, Result, Room,
TransmissionProgress,
};
#[cfg(feature = "e2e-encryption")]
use crate::{
encryption::{Encryption, EncryptionData, EncryptionSettings, VerificationState},
store_locks::CrossProcessStoreLock,
};
mod builder;
pub(crate) mod futures;
pub use self::builder::{sanitize_server_name, ClientBuildError, ClientBuilder};
#[cfg(not(target_arch = "wasm32"))]
type NotificationHandlerFut = Pin<Box<dyn Future<Output = ()> + Send>>;
#[cfg(target_arch = "wasm32")]
type NotificationHandlerFut = Pin<Box<dyn Future<Output = ()>>>;
#[cfg(not(target_arch = "wasm32"))]
type NotificationHandlerFn =
Box<dyn Fn(Notification, Room, Client) -> NotificationHandlerFut + Send + Sync>;
#[cfg(target_arch = "wasm32")]
type NotificationHandlerFn = Box<dyn Fn(Notification, Room, Client) -> NotificationHandlerFut>;
/// Enum controlling if a loop running callbacks should continue or abort.
///
/// This is mainly used in the [`sync_with_callback`] method, the return value
/// of the provided callback controls if the sync loop should be exited.
///
/// [`sync_with_callback`]: #method.sync_with_callback
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoopCtrl {
/// Continue running the loop.
Continue,
/// Break out of the loop.
Break,
}
/// Represents changes that can occur to a `Client`s `Session`.
#[derive(Debug, Clone, PartialEq)]
pub enum SessionChange {
/// The session's token is no longer valid.
UnknownToken {
/// Whether or not the session was soft logged out
soft_logout: bool,
},
/// The session's tokens have been refreshed.
TokensRefreshed,
}
/// An async/await enabled Matrix client.
///
/// All of the state is held in an `Arc` so the `Client` can be cloned freely.
#[derive(Clone)]
pub struct Client {
pub(crate) inner: Arc<ClientInner>,
}
#[derive(Default)]
pub(crate) struct ClientLocks {
/// Lock ensuring that only a single room may be marked as a DM at once.
/// Look at the [`Account::mark_as_dm()`] method for a more detailed
/// explanation.
pub(crate) mark_as_dm_lock: Mutex<()>,
/// Lock ensuring that only a single secret store is getting opened at the
/// same time.
///
/// This is important so we don't accidentally create multiple different new
/// default secret storage keys.
#[cfg(feature = "e2e-encryption")]
pub(crate) open_secret_store_lock: Mutex<()>,
/// Lock ensuring that we're only storing a single secret at a time.
///
/// Take a look at the [`SecretStore::put_secret`] method for a more
/// detailed explanation.
///
/// [`SecretStore::put_secret`]: crate::encryption::secret_storage::SecretStore::put_secret
#[cfg(feature = "e2e-encryption")]
pub(crate) store_secret_lock: Mutex<()>,
/// Lock ensuring that only one method at a time might modify our backup.
#[cfg(feature = "e2e-encryption")]
pub(crate) backup_modify_lock: Mutex<()>,
/// Lock ensuring that we're going to attempt to upload backups for a single
/// requester.
#[cfg(feature = "e2e-encryption")]
pub(crate) backup_upload_lock: Mutex<()>,
/// Handler making sure we only have one group session sharing request in
/// flight per room.
#[cfg(feature = "e2e-encryption")]
pub(crate) group_session_deduplicated_handler: DeduplicatingHandler<OwnedRoomId>,
/// Lock making sure we're only doing one key claim request at a time.
#[cfg(feature = "e2e-encryption")]
pub(crate) key_claim_lock: Mutex<()>,
/// Handler to ensure that only one members request is running at a time,
/// given a room.
pub(crate) members_request_deduplicated_handler: DeduplicatingHandler<OwnedRoomId>,
/// Handler to ensure that only one encryption state request is running at a
/// time, given a room.
pub(crate) encryption_state_deduplicated_handler: DeduplicatingHandler<OwnedRoomId>,
/// Deduplicating handler for sending read receipts. The string is an
/// internal implementation detail, see [`Self::send_single_receipt`].
pub(crate) read_receipt_deduplicated_handler: DeduplicatingHandler<(String, OwnedEventId)>,
#[cfg(feature = "e2e-encryption")]
pub(crate) cross_process_crypto_store_lock:
OnceCell<CrossProcessStoreLock<LockableCryptoStore>>,
/// Latest "generation" of data known by the crypto store.
///
/// This is a counter that only increments, set in the database (and can
/// wrap). It's incremented whenever some process acquires a lock for the
/// first time. *This assumes the crypto store lock is being held, to
/// avoid data races on writing to this value in the store*.
///
/// The current process will maintain this value in local memory and in the
/// DB over time. Observing a different value than the one read in
/// memory, when reading from the store indicates that somebody else has
/// written into the database under our feet.
///
/// TODO: this should live in the `OlmMachine`, since it's information
/// related to the lock. As of today (2023-07-28), we blow up the entire
/// olm machine when there's a generation mismatch. So storing the
/// generation in the olm machine would make the client think there's
/// *always* a mismatch, and that's why we need to store the generation
/// outside the `OlmMachine`.
#[cfg(feature = "e2e-encryption")]
pub(crate) crypto_store_generation: Arc<Mutex<Option<u64>>>,
}
pub(crate) struct ClientInner {
/// All the data related to authentication and authorization.
pub(crate) auth_ctx: Arc<AuthCtx>,
/// The URL of the server.
///
/// Not to be confused with the `Self::homeserver`. `server` is usually
/// the server part in a user ID, e.g. with `@mnt_io:matrix.org`, here
/// `matrix.org` is the server, whilst `matrix-client.matrix.org` is the
/// homeserver (at the time of writing — 2024-08-28).
///
/// This value is optional depending on how the `Client` has been built.
/// If it's been built from a homeserver URL directly, we don't know the
/// server. However, if the `Client` has been built from a server URL or
/// name, then the homeserver has been discovered, and we know both.
server: Option<Url>,
/// The URL of the homeserver to connect to.
///
/// This is the URL for the client-server Matrix API.
homeserver: StdRwLock<Url>,
#[cfg(feature = "experimental-sliding-sync")]
sliding_sync_version: StdRwLock<SlidingSyncVersion>,
/// The underlying HTTP client.
pub(crate) http_client: HttpClient,
/// User session data.
base_client: BaseClient,
/// Server capabilities, either prefilled during building or fetched from
/// the server.
server_capabilities: RwLock<ClientServerCapabilities>,
/// Collection of locks individual client methods might want to use, either
/// to ensure that only a single call to a method happens at once or to
/// deduplicate multiple calls to a method.
pub(crate) locks: ClientLocks,
/// A mapping of the times at which the current user sent typing notices,
/// keyed by room.
pub(crate) typing_notice_times: StdRwLock<BTreeMap<OwnedRoomId, Instant>>,
/// Event handlers. See `add_event_handler`.
pub(crate) event_handlers: EventHandlerStore,
/// Notification handlers. See `register_notification_handler`.
notification_handlers: RwLock<Vec<NotificationHandlerFn>>,
/// The sender-side of channels used to receive room updates.
pub(crate) room_update_channels: StdMutex<BTreeMap<OwnedRoomId, broadcast::Sender<RoomUpdate>>>,
/// The sender-side of a channel used to observe all the room updates of a
/// sync response.
pub(crate) room_updates_sender: broadcast::Sender<RoomUpdates>,
/// Whether the client should update its homeserver URL with the discovery
/// information present in the login response.
respect_login_well_known: bool,
/// An event that can be listened on to wait for a successful sync. The
/// event will only be fired if a sync loop is running. Can be used for
/// synchronization, e.g. if we send out a request to create a room, we can
/// wait for the sync to get the data to fetch a room object from the state
/// store.
pub(crate) sync_beat: event_listener::Event,
/// A central cache for events, inactive first.
///
/// It becomes active when [`EventCache::subscribe`] is called.
pub(crate) event_cache: OnceCell<EventCache>,
/// End-to-end encryption related state.
#[cfg(feature = "e2e-encryption")]
pub(crate) e2ee: EncryptionData,
/// The verification state of our own device.
#[cfg(feature = "e2e-encryption")]
pub(crate) verification_state: SharedObservable<VerificationState>,
/// Data related to the [`SendQueue`].
///
/// [`SendQueue`]: crate::send_queue::SendQueue
pub(crate) send_queue_data: Arc<SendQueueData>,
}
impl ClientInner {
/// Create a new `ClientInner`.
///
/// All the fields passed as parameters here are those that must be cloned
/// upon instantiation of a sub-client, e.g. a client specialized for
/// notifications.
#[allow(clippy::too_many_arguments)]
async fn new(
auth_ctx: Arc<AuthCtx>,
server: Option<Url>,
homeserver: Url,
#[cfg(feature = "experimental-sliding-sync")] sliding_sync_version: SlidingSyncVersion,
http_client: HttpClient,
base_client: BaseClient,
server_capabilities: ClientServerCapabilities,
respect_login_well_known: bool,
event_cache: OnceCell<EventCache>,
send_queue: Arc<SendQueueData>,
#[cfg(feature = "e2e-encryption")] encryption_settings: EncryptionSettings,
) -> Arc<Self> {
let client = Self {
server,
homeserver: StdRwLock::new(homeserver),
auth_ctx,
#[cfg(feature = "experimental-sliding-sync")]
sliding_sync_version: StdRwLock::new(sliding_sync_version),
http_client,
base_client,
locks: Default::default(),
server_capabilities: RwLock::new(server_capabilities),
typing_notice_times: Default::default(),
event_handlers: Default::default(),
notification_handlers: Default::default(),
room_update_channels: Default::default(),
// A single `RoomUpdates` is sent once per sync, so we assume that 32 is sufficient
// ballast for all observers to catch up.
room_updates_sender: broadcast::Sender::new(32),
respect_login_well_known,
sync_beat: event_listener::Event::new(),
event_cache,
send_queue_data: send_queue,
#[cfg(feature = "e2e-encryption")]
e2ee: EncryptionData::new(encryption_settings),
#[cfg(feature = "e2e-encryption")]
verification_state: SharedObservable::new(VerificationState::Unknown),
};
#[allow(clippy::let_and_return)]
let client = Arc::new(client);
#[cfg(feature = "e2e-encryption")]
client.e2ee.initialize_room_key_tasks(&client);
let _ = client
.event_cache
.get_or_init(|| async { EventCache::new(WeakClient::from_inner(&client)) })
.await;
client
}
}
#[cfg(not(tarpaulin_include))]
impl Debug for Client {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(fmt, "Client")
}
}
impl Client {
/// Create a new [`Client`] that will use the given homeserver.
///
/// # Arguments
///
/// * `homeserver_url` - The homeserver that the client should connect to.
pub async fn new(homeserver_url: Url) -> Result<Self, HttpError> {
Self::builder()
.homeserver_url(homeserver_url)
.build()
.await
.map_err(ClientBuildError::assert_valid_builder_args)
}
/// Returns a subscriber that publishes an event every time the ignore user
/// list changes.
pub fn subscribe_to_ignore_user_list_changes(&self) -> Subscriber<Vec<String>> {
self.inner.base_client.subscribe_to_ignore_user_list_changes()
}
/// Create a new [`ClientBuilder`].
pub fn builder() -> ClientBuilder {
ClientBuilder::new()
}
pub(crate) fn base_client(&self) -> &BaseClient {
&self.inner.base_client
}
/// The underlying HTTP client.
pub fn http_client(&self) -> &reqwest::Client {
&self.inner.http_client.inner
}
pub(crate) fn locks(&self) -> &ClientLocks {
&self.inner.locks
}
/// Change the homeserver URL used by this client.
///
/// # Arguments
///
/// * `homeserver_url` - The new URL to use.
fn set_homeserver(&self, homeserver_url: Url) {
*self.inner.homeserver.write().unwrap() = homeserver_url;
}
/// Get the capabilities of the homeserver.
///
/// This method should be used to check what features are supported by the
/// homeserver.
///
/// # Examples
///
/// ```no_run
/// # use matrix_sdk::Client;
/// # use url::Url;
/// # async {
/// # let homeserver = Url::parse("http://example.com")?;
/// let client = Client::new(homeserver).await?;
///
/// let capabilities = client.get_capabilities().await?;
///
/// if capabilities.change_password.enabled {
/// // Change password
/// }
/// # anyhow::Ok(()) };
/// ```
pub async fn get_capabilities(&self) -> HttpResult<Capabilities> {
let res = self.send(get_capabilities::v3::Request::new(), None).await?;
Ok(res.capabilities)
}
/// Get a copy of the default request config.
///
/// The default request config is what's used when sending requests if no
/// `RequestConfig` is explicitly passed to [`send`][Self::send] or another
/// function with such a parameter.
///
/// If the default request config was not customized through
/// [`ClientBuilder`] when creating this `Client`, the returned value will
/// be equivalent to [`RequestConfig::default()`].
pub fn request_config(&self) -> RequestConfig {
self.inner.http_client.request_config
}
/// Is the client logged in.
pub fn logged_in(&self) -> bool {
self.inner.base_client.logged_in()
}
/// The server used by the client.
///
/// See `Self::server` to learn more.
pub fn server(&self) -> Option<&Url> {
self.inner.server.as_ref()
}
/// The homeserver of the client.
pub fn homeserver(&self) -> Url {
self.inner.homeserver.read().unwrap().clone()
}
/// Get the sliding sync version.
#[cfg(feature = "experimental-sliding-sync")]
pub fn sliding_sync_version(&self) -> SlidingSyncVersion {
self.inner.sliding_sync_version.read().unwrap().clone()
}
/// Override the sliding sync version.
#[cfg(feature = "experimental-sliding-sync")]
pub fn set_sliding_sync_version(&self, version: SlidingSyncVersion) {
let mut lock = self.inner.sliding_sync_version.write().unwrap();
*lock = version;
}
/// Get the Matrix user session meta information.
///
/// If the client is currently logged in, this will return a
/// [`SessionMeta`] object which contains the user ID and device ID.
/// Otherwise it returns `None`.
pub fn session_meta(&self) -> Option<&SessionMeta> {
self.base_client().session_meta()
}
/// Returns a receiver that gets events for each room info update. To watch
/// for new events, use `receiver.resubscribe()`. Each event contains the
/// room and a boolean whether this event should trigger a room list update.
pub fn room_info_notable_update_receiver(&self) -> broadcast::Receiver<RoomInfoNotableUpdate> {
self.base_client().room_info_notable_update_receiver()
}
/// Performs a search for users.
/// The search is performed case-insensitively on user IDs and display names
///
/// # Arguments
///
/// * `search_term` - The search term for the search
/// * `limit` - The maximum number of results to return. Defaults to 10.
///
/// [user directory]: https://spec.matrix.org/v1.6/client-server-api/#user-directory
pub async fn search_users(
&self,
search_term: &str,
limit: u64,
) -> HttpResult<search_users::v3::Response> {
let mut request = search_users::v3::Request::new(search_term.to_owned());
if let Some(limit) = UInt::new(limit) {
request.limit = limit;
}
self.send(request, None).await
}
/// Get the user id of the current owner of the client.
pub fn user_id(&self) -> Option<&UserId> {
self.session_meta().map(|s| s.user_id.as_ref())
}
/// Get the device ID that identifies the current session.
pub fn device_id(&self) -> Option<&DeviceId> {
self.session_meta().map(|s| s.device_id.as_ref())
}
/// Get the current access token for this session, regardless of the
/// authentication API used to log in.
///
/// Will be `None` if the client has not been logged in.
pub fn access_token(&self) -> Option<String> {
self.inner.auth_ctx.auth_data.get()?.access_token()
}
/// Access the authentication API used to log in this client.
///
/// Will be `None` if the client has not been logged in.
pub fn auth_api(&self) -> Option<AuthApi> {
match self.inner.auth_ctx.auth_data.get()? {
AuthData::Matrix(_) => Some(AuthApi::Matrix(self.matrix_auth())),
#[cfg(feature = "experimental-oidc")]
AuthData::Oidc(_) => Some(AuthApi::Oidc(self.oidc())),
}
}
/// Get the whole session info of this client.
///
/// Will be `None` if the client has not been logged in.
///
/// Can be used with [`Client::restore_session`] to restore a previously
/// logged-in session.
pub fn session(&self) -> Option<AuthSession> {
match self.auth_api()? {
AuthApi::Matrix(api) => api.session().map(Into::into),
#[cfg(feature = "experimental-oidc")]
AuthApi::Oidc(api) => api.full_session().map(Into::into),
}
}
/// Get a reference to the state store.
pub fn store(&self) -> &DynStateStore {
self.base_client().store()
}
/// Get a reference to the event cache store.
pub(crate) fn event_cache_store(&self) -> &DynEventCacheStore {
self.base_client().event_cache_store()
}
/// Access the native Matrix authentication API with this client.
pub fn matrix_auth(&self) -> MatrixAuth {
MatrixAuth::new(self.clone())
}
/// Get the account of the current owner of the client.
pub fn account(&self) -> Account {
Account::new(self.clone())
}
/// Get the encryption manager of the client.
#[cfg(feature = "e2e-encryption")]
pub fn encryption(&self) -> Encryption {
Encryption::new(self.clone())
}
/// Get the media manager of the client.
pub fn media(&self) -> Media {
Media::new(self.clone())
}
/// Get the pusher manager of the client.
pub fn pusher(&self) -> Pusher {
Pusher::new(self.clone())
}
/// Access the OpenID Connect API of the client.
#[cfg(feature = "experimental-oidc")]
pub fn oidc(&self) -> Oidc {
Oidc::new(self.clone())
}
/// Register a handler for a specific event type.
///
/// The handler is a function or closure with one or more arguments. The
/// first argument is the event itself. All additional arguments are
/// "context" arguments: They have to implement [`EventHandlerContext`].
/// This trait is named that way because most of the types implementing it
/// give additional context about an event: The room it was in, its raw form
/// and other similar things. As two exceptions to this,
/// [`Client`] and [`EventHandlerHandle`] also implement the
/// `EventHandlerContext` trait so you don't have to clone your client
/// into the event handler manually and a handler can decide to remove
/// itself.
///
/// Some context arguments are not universally applicable. A context
/// argument that isn't available for the given event type will result in
/// the event handler being skipped and an error being logged. The following
/// context argument types are only available for a subset of event types:
///
/// * [`Room`] is only available for room-specific events, i.e. not for
/// events like global account data events or presence events.
///
/// You can provide custom context via
/// [`add_event_handler_context`](Client::add_event_handler_context) and
/// then use [`Ctx<T>`](crate::event_handler::Ctx) to extract the context
/// into the event handler.
///
/// [`EventHandlerContext`]: crate::event_handler::EventHandlerContext
///
/// # Examples
///
/// ```no_run
/// # use url::Url;
/// # let homeserver = Url::parse("http://localhost:8080").unwrap();
/// use matrix_sdk::{
/// deserialized_responses::EncryptionInfo,
/// event_handler::Ctx,
/// ruma::{
/// events::{
/// macros::EventContent,
/// push_rules::PushRulesEvent,
/// room::{message::SyncRoomMessageEvent, topic::SyncRoomTopicEvent},
/// },
/// push::Action,
/// Int, MilliSecondsSinceUnixEpoch,
/// },
/// Client, Room,
/// };
/// use serde::{Deserialize, Serialize};
///
/// # futures_executor::block_on(async {
/// # let client = matrix_sdk::Client::builder()
/// # .homeserver_url(homeserver)
/// # .server_versions([ruma::api::MatrixVersion::V1_0])
/// # .build()
/// # .await
/// # .unwrap();
/// #
/// client.add_event_handler(
/// |ev: SyncRoomMessageEvent, room: Room, client: Client| async move {
/// // Common usage: Room event plus room and client.
/// },
/// );
/// client.add_event_handler(
/// |ev: SyncRoomMessageEvent, room: Room, encryption_info: Option<EncryptionInfo>| {
/// async move {
/// // An `Option<EncryptionInfo>` parameter lets you distinguish between
/// // unencrypted events and events that were decrypted by the SDK.
/// }
/// },
/// );
/// client.add_event_handler(
/// |ev: SyncRoomMessageEvent, room: Room, push_actions: Vec<Action>| {
/// async move {
/// // A `Vec<Action>` parameter allows you to know which push actions
/// // are applicable for an event. For example, an event with
/// // `Action::SetTweak(Tweak::Highlight(true))` should be highlighted
/// // in the timeline.
/// }
/// },
/// );
/// client.add_event_handler(|ev: SyncRoomTopicEvent| async move {
/// // You can omit any or all arguments after the first.
/// });
///
/// // Registering a temporary event handler:
/// let handle = client.add_event_handler(|ev: SyncRoomMessageEvent| async move {
/// /* Event handler */
/// });
/// client.remove_event_handler(handle);
///
/// // Registering custom event handler context:
/// #[derive(Debug, Clone)] // The context will be cloned for event handler.
/// struct MyContext {
/// number: usize,
/// }
/// client.add_event_handler_context(MyContext { number: 5 });
/// client.add_event_handler(|ev: SyncRoomMessageEvent, context: Ctx<MyContext>| async move {
/// // Use the context
/// });
///
/// // Custom events work exactly the same way, you just need to declare
/// // the content struct and use the EventContent derive macro on it.
/// #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
/// #[ruma_event(type = "org.shiny_new_2fa.token", kind = MessageLike)]
/// struct TokenEventContent {
/// token: String,
/// #[serde(rename = "exp")]
/// expires_at: MilliSecondsSinceUnixEpoch,
/// }
///
/// client.add_event_handler(|ev: SyncTokenEvent, room: Room| async move {
/// todo!("Display the token");
/// });
///
/// // Event handler closures can also capture local variables.
/// // Make sure they are cheap to clone though, because they will be cloned
/// // every time the closure is called.
/// let data: std::sync::Arc<str> = "MyCustomIdentifier".into();
///
/// client.add_event_handler(move |ev: SyncRoomMessageEvent | async move {
/// println!("Calling the handler with identifier {data}");
/// });
/// # });
/// ```
pub fn add_event_handler<Ev, Ctx, H>(&self, handler: H) -> EventHandlerHandle
where
Ev: SyncEvent + DeserializeOwned + Send + 'static,
H: EventHandler<Ev, Ctx>,
{
self.add_event_handler_impl(handler, None)
}
/// Register a handler for a specific room, and event type.
///
/// This method works the same way as
/// [`add_event_handler`][Self::add_event_handler], except that the handler
/// will only be called for events in the room with the specified ID. See
/// that method for more details on event handler functions.
///
/// `client.add_room_event_handler(room_id, hdl)` is equivalent to
/// `room.add_event_handler(hdl)`. Use whichever one is more convenient in
/// your use case.
pub fn add_room_event_handler<Ev, Ctx, H>(
&self,
room_id: &RoomId,
handler: H,
) -> EventHandlerHandle
where
Ev: SyncEvent + DeserializeOwned + Send + 'static,
H: EventHandler<Ev, Ctx>,
{
self.add_event_handler_impl(handler, Some(room_id.to_owned()))
}
/// Remove the event handler associated with the handle.
///
/// Note that you **must not** call `remove_event_handler` from the
/// non-async part of an event handler, that is:
///
/// ```ignore
/// client.add_event_handler(|ev: SomeEvent, client: Client, handle: EventHandlerHandle| {
/// // ⚠ this will cause a deadlock ⚠
/// client.remove_event_handler(handle);
///
/// async move {
/// // removing the event handler here is fine
/// client.remove_event_handler(handle);
/// }
/// })
/// ```
///
/// Note also that handlers that remove themselves will still execute with
/// events received in the same sync cycle.
///
/// # Arguments
///
/// `handle` - The [`EventHandlerHandle`] that is returned when
/// registering the event handler with [`Client::add_event_handler`].
///
/// # Examples
///
/// ```no_run
/// # use url::Url;
/// # use tokio::sync::mpsc;
/// #
/// # let homeserver = Url::parse("http://localhost:8080").unwrap();
/// #
/// use matrix_sdk::{
/// event_handler::EventHandlerHandle,
/// ruma::events::room::member::SyncRoomMemberEvent, Client,
/// };
/// #
/// # futures_executor::block_on(async {
/// # let client = matrix_sdk::Client::builder()
/// # .homeserver_url(homeserver)
/// # .server_versions([ruma::api::MatrixVersion::V1_0])
/// # .build()
/// # .await
/// # .unwrap();
///
/// client.add_event_handler(
/// |ev: SyncRoomMemberEvent,
/// client: Client,
/// handle: EventHandlerHandle| async move {
/// // Common usage: Check arriving Event is the expected one
/// println!("Expected RoomMemberEvent received!");
/// client.remove_event_handler(handle);
/// },
/// );
/// # });
/// ```
pub fn remove_event_handler(&self, handle: EventHandlerHandle) {
self.inner.event_handlers.remove(handle);
}
/// Create an [`EventHandlerDropGuard`] for the event handler identified by
/// the given handle.
///
/// When the returned value is dropped, the event handler will be removed.
pub fn event_handler_drop_guard(&self, handle: EventHandlerHandle) -> EventHandlerDropGuard {
EventHandlerDropGuard::new(handle, self.clone())
}
/// Add an arbitrary value for use as event handler context.
///
/// The value can be obtained in an event handler by adding an argument of
/// the type [`Ctx<T>`][crate::event_handler::Ctx].
///
/// If a value of the same type has been added before, it will be
/// overwritten.
///
/// # Examples
///
/// ```no_run
/// use matrix_sdk::{
/// event_handler::Ctx, ruma::events::room::message::SyncRoomMessageEvent,
/// Room,
/// };
/// # #[derive(Clone)]
/// # struct SomeType;
/// # fn obtain_gui_handle() -> SomeType { SomeType }
/// # let homeserver = url::Url::parse("http://localhost:8080").unwrap();
/// # futures_executor::block_on(async {
/// # let client = matrix_sdk::Client::builder()
/// # .homeserver_url(homeserver)
/// # .server_versions([ruma::api::MatrixVersion::V1_0])
/// # .build()
/// # .await
/// # .unwrap();
///
/// // Handle used to send messages to the UI part of the app
/// let my_gui_handle: SomeType = obtain_gui_handle();
///
/// client.add_event_handler_context(my_gui_handle.clone());
/// client.add_event_handler(
/// |ev: SyncRoomMessageEvent, room: Room, gui_handle: Ctx<SomeType>| {
/// async move {
/// // gui_handle.send(DisplayMessage { message: ev });
/// }
/// },
/// );
/// # });
/// ```
pub fn add_event_handler_context<T>(&self, ctx: T)
where
T: Clone + Send + Sync + 'static,
{
self.inner.event_handlers.add_context(ctx);
}
/// Register a handler for a notification.
///
/// Similar to [`Client::add_event_handler`], but only allows functions
/// or closures with exactly the three arguments [`Notification`], [`Room`],
/// [`Client`] for now.
pub async fn register_notification_handler<H, Fut>(&self, handler: H) -> &Self
where
H: Fn(Notification, Room, Client) -> Fut + SendOutsideWasm + SyncOutsideWasm + 'static,
Fut: Future<Output = ()> + SendOutsideWasm + 'static,
{
self.inner.notification_handlers.write().await.push(Box::new(
move |notification, room, client| Box::pin((handler)(notification, room, client)),
));
self
}
/// Subscribe to all updates for the room with the given ID.
///
/// The returned receiver will receive a new message for each sync response
/// that contains updates for that room.
pub fn subscribe_to_room_updates(&self, room_id: &RoomId) -> broadcast::Receiver<RoomUpdate> {
match self.inner.room_update_channels.lock().unwrap().entry(room_id.to_owned()) {
btree_map::Entry::Vacant(entry) => {
let (tx, rx) = broadcast::channel(8);
entry.insert(tx);
rx
}
btree_map::Entry::Occupied(entry) => entry.get().subscribe(),
}
}
/// Subscribe to all updates to all rooms, whenever any has been received in
/// a sync response.
pub fn subscribe_to_all_room_updates(&self) -> broadcast::Receiver<RoomUpdates> {
self.inner.room_updates_sender.subscribe()
}
pub(crate) async fn notification_handlers(
&self,
) -> RwLockReadGuard<'_, Vec<NotificationHandlerFn>> {
self.inner.notification_handlers.read().await
}
/// Get all the rooms the client knows about.
///
/// This will return the list of joined, invited, and left rooms.
pub fn rooms(&self) -> Vec<Room> {
self.base_client().rooms().into_iter().map(|room| Room::new(self.clone(), room)).collect()
}
/// Get all the rooms the client knows about, filtered by room state.
pub fn rooms_filtered(&self, filter: RoomStateFilter) -> Vec<Room> {
self.base_client()
.rooms_filtered(filter)
.into_iter()
.map(|room| Room::new(self.clone(), room))
.collect()
}
/// Get a stream of all the rooms, in addition to the existing rooms.
#[cfg(not(target_arch = "wasm32"))]
pub fn rooms_stream(&self) -> (Vector<Room>, impl Stream<Item = Vec<VectorDiff<Room>>> + '_) {
let (rooms, stream) = self.base_client().rooms_stream();
let map_room = |room| Room::new(self.clone(), room);
(
rooms.into_iter().map(map_room).collect(),
stream.map(move |diffs| diffs.into_iter().map(|diff| diff.map(map_room)).collect()),
)
}
/// Returns the joined rooms this client knows about.
pub fn joined_rooms(&self) -> Vec<Room> {
self.base_client()
.rooms_filtered(RoomStateFilter::JOINED)
.into_iter()
.map(|room| Room::new(self.clone(), room))
.collect()
}
/// Returns the invited rooms this client knows about.
pub fn invited_rooms(&self) -> Vec<Room> {
self.base_client()
.rooms_filtered(RoomStateFilter::INVITED)
.into_iter()
.map(|room| Room::new(self.clone(), room))
.collect()
}
/// Returns the left rooms this client knows about.
pub fn left_rooms(&self) -> Vec<Room> {
self.base_client()
.rooms_filtered(RoomStateFilter::LEFT)
.into_iter()
.map(|room| Room::new(self.clone(), room))
.collect()
}
/// Get a room with the given room id.
///
/// # Arguments
///
/// `room_id` - The unique id of the room that should be fetched.
pub fn get_room(&self, room_id: &RoomId) -> Option<Room> {
self.base_client().get_room(room_id).map(|room| Room::new(self.clone(), room))
}