-
Notifications
You must be signed in to change notification settings - Fork 274
/
Copy pathmod.rs
2582 lines (2409 loc) · 92.6 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::{
fmt::{self, Debug},
future::Future,
pin::Pin,
sync::Arc,
};
#[cfg(target_arch = "wasm32")]
use async_once_cell::OnceCell;
use dashmap::DashMap;
use futures_core::stream::Stream;
use futures_signals::signal::Signal;
use matrix_sdk_base::{
BaseClient, RoomType, SendOutsideWasm, Session, SessionMeta, SessionTokens, StateStore,
SyncOutsideWasm,
};
use matrix_sdk_common::{
instant::Instant,
locks::{Mutex, RwLock, RwLockReadGuard},
};
#[cfg(feature = "appservice")]
use ruma::TransactionId;
use ruma::{
api::{
client::{
account::{register, whoami},
alias::get_alias,
device::{delete_devices, get_devices},
directory::{get_public_rooms, get_public_rooms_filtered},
discovery::{
get_capabilities::{self, Capabilities},
get_supported_versions,
},
error::ErrorKind,
filter::{create_filter::v3::Request as FilterUploadRequest, FilterDefinition},
membership::{join_room_by_id, join_room_by_id_or_alias},
push::get_notifications::v3::Notification,
room::create_room,
session::{
get_login_types, login, logout, refresh_token, sso_login, sso_login_with_provider,
},
sync::sync_events,
uiaa::{AuthData, UserIdentifier},
},
error::FromHttpResponseError,
MatrixVersion, OutgoingRequest, SendAccessToken,
},
assign, DeviceId, OwnedDeviceId, OwnedRoomId, OwnedServerName, RoomAliasId, RoomId,
RoomOrAliasId, ServerName, UInt, UserId,
};
use serde::de::DeserializeOwned;
#[cfg(not(target_arch = "wasm32"))]
use tokio::sync::OnceCell;
#[cfg(feature = "e2e-encryption")]
use tracing::error;
use tracing::{debug, field::display, info, instrument, trace, Instrument, Span};
use url::Url;
#[cfg(feature = "e2e-encryption")]
use crate::encryption::Encryption;
use crate::{
config::RequestConfig,
error::{HttpError, HttpResult},
event_handler::{
EventHandler, EventHandlerDropGuard, EventHandlerHandle, EventHandlerStore, SyncEvent,
},
http_client::HttpClient,
room,
sync::SyncResponse,
Account, Error, Media, RefreshTokenError, Result, RumaApiError,
};
mod builder;
mod login_builder;
#[cfg(feature = "sso-login")]
pub use self::login_builder::SsoLoginBuilder;
pub use self::{
builder::{ClientBuildError, ClientBuilder},
login_builder::LoginBuilder,
};
#[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::Room, Client) -> NotificationHandlerFut + Send + Sync>;
#[cfg(target_arch = "wasm32")]
type NotificationHandlerFn =
Box<dyn Fn(Notification, room::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,
}
/// 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>,
pub(crate) root_span: Span,
}
pub(crate) struct ClientInner {
/// The URL of the homeserver to connect to.
homeserver: RwLock<Url>,
/// The OIDC Provider that is trusted by the homeserver.
authentication_issuer: Option<RwLock<Url>>,
/// The sliding sync proxy that is trusted by the homeserver.
#[cfg(feature = "experimental-sliding-sync")]
sliding_sync_proxy: Option<RwLock<Url>>,
/// The underlying HTTP client.
http_client: HttpClient,
/// User session data.
base_client: BaseClient,
/// The Matrix versions the server supports (well-known ones only)
server_versions: OnceCell<Box<[MatrixVersion]>>,
/// Locks making sure we only have one group session sharing request in
/// flight per room.
#[cfg(feature = "e2e-encryption")]
pub(crate) group_session_locks: DashMap<OwnedRoomId, Arc<Mutex<()>>>,
/// Lock making sure we're only doing one key claim request at a time.
#[cfg(feature = "e2e-encryption")]
pub(crate) key_claim_lock: Mutex<()>,
pub(crate) members_request_locks: DashMap<OwnedRoomId, Arc<Mutex<()>>>,
/// Locks for requests on the encryption state of rooms.
pub(crate) encryption_state_request_locks: DashMap<OwnedRoomId, Arc<Mutex<()>>>,
pub(crate) typing_notice_times: DashMap<OwnedRoomId, Instant>,
/// Event handlers. See `add_event_handler`.
pub(crate) event_handlers: EventHandlerStore,
/// Notification handlers. See `register_notification_handler`.
notification_handlers: RwLock<Vec<NotificationHandlerFn>>,
/// Whether the client should operate in application service style mode.
/// This is low-level functionality. For an high-level API check the
/// `matrix_sdk_appservice` crate.
appservice_mode: bool,
/// Whether the client should update its homeserver URL with the discovery
/// information present in the login response.
respect_login_well_known: bool,
/// Whether to try to refresh the access token automatically when an
/// `M_UNKNOWN_TOKEN` error is encountered.
handle_refresh_tokens: bool,
/// Lock making sure we're only doing one token refresh at a time.
refresh_token_lock: Mutex<Result<(), RefreshTokenError>>,
/// 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,
}
#[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)
}
/// Create a new [`ClientBuilder`].
pub fn builder() -> ClientBuilder {
ClientBuilder::new()
}
pub(crate) fn base_client(&self) -> &BaseClient {
&self.inner.base_client
}
/// Change the homeserver URL used by this client.
///
/// # Arguments
///
/// * `homeserver_url` - The new URL to use.
async fn set_homeserver(&self, homeserver_url: Url) {
let mut homeserver = self.inner.homeserver.write().await;
*homeserver = homeserver_url;
}
/// Get the capabilities of the homeserver.
///
/// This method should be used to check what features are supported by the
/// homeserver.
///
/// # Example
/// ```no_run
/// # use futures::executor::block_on;
/// # use matrix_sdk::Client;
/// # use url::Url;
/// # block_on(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)
}
/// Process a [transaction] received from the homeserver which has been
/// converted into a sync response.
///
/// # Arguments
///
/// * `transaction_id` - The id of the transaction, used to guard against
/// the same transaction being sent twice. This guarding currently isn't
/// implemented.
/// * `sync_response` - The sync response converted from a transaction
/// received from the homeserver.
///
/// [transaction]: https://matrix.org/docs/spec/application_service/r0.1.2#put-matrix-app-v1-transactions-txnid
#[cfg(feature = "appservice")]
pub async fn receive_transaction(
&self,
transaction_id: &TransactionId,
sync_response: sync_events::v3::Response,
) -> Result<()> {
const TXN_ID_KEY: &[u8] = b"appservice.txn_id";
let store = self.store();
let store_tokens = store.get_custom_value(TXN_ID_KEY).await?;
let mut txn_id_bytes = transaction_id.as_bytes().to_vec();
if let Some(mut store_tokens) = store_tokens {
// The data is separated by a NULL byte.
let mut store_tokens_split = store_tokens.split(|x| *x == b'\0');
if store_tokens_split.any(|x| x == transaction_id.as_bytes()) {
// We already encountered this transaction id before, so we exit early instead
// of processing further.
//
// Spec: https://spec.matrix.org/v1.3/application-service-api/#pushing-events
return Ok(());
}
store_tokens.push(b'\0');
store_tokens.append(&mut txn_id_bytes);
self.store().set_custom_value(TXN_ID_KEY, store_tokens).await?;
} else {
self.store().set_custom_value(TXN_ID_KEY, txn_id_bytes).await?;
}
self.process_sync(sync_response).await?;
Ok(())
}
/// 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 Homeserver of the client.
pub async fn homeserver(&self) -> Url {
self.inner.homeserver.read().await.clone()
}
/// The OIDC Provider that is trusted by the homeserver.
pub async fn authentication_issuer(&self) -> Option<Url> {
let server = self.inner.authentication_issuer.as_ref()?;
Some(server.read().await.clone())
}
/// The sliding sync proxy that is trusted by the homeserver.
#[cfg(feature = "experimental-sliding-sync")]
pub async fn sliding_sync_proxy(&self) -> Option<Url> {
let server = self.inner.sliding_sync_proxy.as_ref()?;
Some(server.read().await.clone())
}
fn session_meta(&self) -> Option<&SessionMeta> {
self.base_client().session_meta()
}
/// 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 and optional refresh token for this
/// session.
///
/// Will be `None` if the client has not been logged in.
///
/// After login, the tokens should only change if support for [refreshing
/// access tokens] has been enabled.
///
/// [refreshing access tokens]: https://spec.matrix.org/v1.3/client-server-api/#refreshing-access-tokens
pub fn session_tokens(&self) -> Option<SessionTokens> {
self.base_client().session_tokens().get_cloned()
}
/// Get the current access token for this session.
///
/// Will be `None` if the client has not been logged in.
///
/// After login, this token should only change if support for [refreshing
/// access tokens] has been enabled.
///
/// [refreshing access tokens]: https://spec.matrix.org/v1.3/client-server-api/#refreshing-access-tokens
pub fn access_token(&self) -> Option<String> {
self.session_tokens().map(|tokens| tokens.access_token)
}
/// Get the current refresh token for this session.
///
/// Will be `None` if the client has not been logged in, or if the access
/// token doesn't expire.
///
/// After login, this token should only change if support for [refreshing
/// access tokens] has been enabled.
///
/// [refreshing access tokens]: https://spec.matrix.org/v1.3/client-server-api/#refreshing-access-tokens
pub fn refresh_token(&self) -> Option<String> {
self.session_tokens().and_then(|tokens| tokens.refresh_token)
}
/// [`Signal`] to get notified when the current access token and optional
/// refresh token for this session change.
///
/// This can be used with [`Client::session()`] to persist the [`Session`]
/// when the tokens change.
///
/// After login, the tokens should only change if support for [refreshing
/// access tokens] has been enabled.
///
/// # Example
///
/// ```no_run
/// use futures_signals::signal::SignalExt;
/// use matrix_sdk::Client;
/// # use matrix_sdk::Session;
/// # use futures::executor::block_on;
/// # block_on(async {
/// # fn persist_session(_: Option<Session>) {};
///
/// let homeserver = "http://example.com";
/// let client = Client::builder()
/// .homeserver_url(homeserver)
/// .handle_refresh_tokens()
/// .build()
/// .await?;
///
/// let response = client
/// .login_username("user", "wordpass")
/// .initial_device_display_name("My App")
/// .request_refresh_token()
/// .send()
/// .await?;
///
/// persist_session(client.session());
///
/// // Handle when at least one of the tokens changed.
/// let future = client.session_tokens_changed_signal().for_each(move |_| {
/// let client = client.clone();
/// async move {
/// persist_session(client.session());
/// }
/// });
///
/// tokio::spawn(future);
///
/// # anyhow::Ok(()) });
/// ```
///
/// [refreshing access tokens]: https://spec.matrix.org/v1.3/client-server-api/#refreshing-access-tokens
pub fn session_tokens_changed_signal(&self) -> impl Signal<Item = ()> {
self.base_client().session_tokens().signal_ref(|_| ())
}
/// Get the current access token and optional refresh token for this
/// session as a [`Signal`].
///
/// This can be used to watch changes of the tokens by calling methods like
/// `for_each()` or `to_stream()`.
///
/// The value will be `None` if the client has not been logged in.
///
/// After login, the tokens should only change if support for [refreshing
/// access tokens] has been enabled.
///
/// # Example
///
/// ```no_run
/// use futures::StreamExt;
/// use futures_signals::signal::SignalExt;
/// use matrix_sdk::Client;
/// # use matrix_sdk::Session;
/// # use futures::executor::block_on;
/// # block_on(async {
/// # fn persist_session(_: &Session) {};
///
/// let homeserver = "http://example.com";
/// let client = Client::builder()
/// .homeserver_url(homeserver)
/// .handle_refresh_tokens()
/// .build()
/// .await?;
///
/// client
/// .login_username("user", "wordpass")
/// .initial_device_display_name("My App")
/// .request_refresh_token()
/// .send()
/// .await?;
///
/// let mut session = client.session().expect("Client should be logged in");
/// persist_session(&session);
///
/// // Handle when at least one of the tokens changed.
/// let mut tokens_stream = client.session_tokens_signal().to_stream();
/// loop {
/// if let Some(tokens) = tokens_stream.next().await.flatten() {
/// session.access_token = tokens.access_token;
///
/// if let Some(refresh_token) = tokens.refresh_token {
/// session.refresh_token = Some(refresh_token);
/// }
///
/// persist_session(&session);
/// }
/// }
///
/// # anyhow::Ok(()) });
/// ```
///
/// [refreshing access tokens]: https://spec.matrix.org/v1.3/client-server-api/#refreshing-access-tokens
pub fn session_tokens_signal(&self) -> impl Signal<Item = Option<SessionTokens>> {
self.base_client().session_tokens().signal_cloned()
}
/// 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<Session> {
self.base_client().session()
}
/// Get a reference to the state store.
pub fn store(&self) -> &dyn StateStore {
self.base_client().store()
}
/// 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())
}
/// 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`][room::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
///
/// ```
/// # use futures::executor::block_on;
/// # use url::Url;
/// # let homeserver = Url::parse("http://localhost:8080").unwrap();
/// use matrix_sdk::{
/// deserialized_responses::EncryptionInfo,
/// event_handler::Ctx,
/// room::Room,
/// ruma::{
/// events::{
/// macros::EventContent,
/// push_rules::PushRulesEvent,
/// room::{message::SyncRoomMessageEvent, topic::SyncRoomTopicEvent},
/// },
/// Int, MilliSecondsSinceUnixEpoch,
/// },
/// Client,
/// };
/// use serde::{Deserialize, Serialize};
///
/// # 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: 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");
/// });
///
/// // Adding your custom data to the handler can be done as well
/// let data = "MyCustomIdentifier".to_owned();
///
/// client.add_event_handler({
/// let data = data.clone();
/// move |ev: SyncRoomMessageEvent | {
/// let data = data.clone();
/// 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
///
/// ```
/// # use futures::executor::block_on;
/// # 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,
/// };
/// #
/// # 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.
///
/// # Example
///
/// ```
/// # use futures::executor::block_on;
/// use matrix_sdk::{
/// event_handler::Ctx, room::Room,
/// ruma::events::room::message::SyncRoomMessageEvent,
/// };
/// # #[derive(Clone)]
/// # struct SomeType;
/// # fn obtain_gui_handle() -> SomeType { SomeType }
/// # let homeserver = url::Url::parse("http://localhost:8080").unwrap();
/// # 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::Room`], [`Client`] for now.
pub async fn register_notification_handler<H, Fut>(&self, handler: H) -> &Self
where
H: Fn(Notification, room::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
}
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::Room> {
self.base_client()
.get_rooms()
.into_iter()
.map(|room| room::Common::new(self.clone(), room).into())
.collect()
}
/// Returns the joined rooms this client knows about.
pub fn joined_rooms(&self) -> Vec<room::Joined> {
self.base_client()
.get_rooms()
.into_iter()
.filter_map(|room| room::Joined::new(self, room))
.collect()
}
/// Returns the invited rooms this client knows about.
pub fn invited_rooms(&self) -> Vec<room::Invited> {
self.base_client()
.get_stripped_rooms()
.into_iter()
.filter_map(|room| room::Invited::new(self, room))
.collect()
}
/// Returns the left rooms this client knows about.
pub fn left_rooms(&self) -> Vec<room::Left> {
self.base_client()
.get_rooms()
.into_iter()
.filter_map(|room| room::Left::new(self, 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::Room> {
self.base_client()
.get_room(room_id)
.map(|room| room::Common::new(self.clone(), room).into())
}
/// Get a joined room with the given room id.
///
/// # Arguments
///
/// `room_id` - The unique id of the room that should be fetched.
pub fn get_joined_room(&self, room_id: &RoomId) -> Option<room::Joined> {
self.base_client().get_room(room_id).and_then(|room| room::Joined::new(self, room))
}
/// Get an invited room with the given room id.
///
/// # Arguments
///
/// `room_id` - The unique id of the room that should be fetched.
pub fn get_invited_room(&self, room_id: &RoomId) -> Option<room::Invited> {
self.base_client().get_room(room_id).and_then(|room| room::Invited::new(self, room))
}
/// Get a left room with the given room id.
///
/// # Arguments
///
/// `room_id` - The unique id of the room that should be fetched.
pub fn get_left_room(&self, room_id: &RoomId) -> Option<room::Left> {
self.base_client().get_room(room_id).and_then(|room| room::Left::new(self, room))
}
/// Resolve a room alias to a room id and a list of servers which know
/// about it.
///
/// # Arguments
///
/// `room_alias` - The room alias to be resolved.
pub async fn resolve_room_alias(
&self,
room_alias: &RoomAliasId,
) -> HttpResult<get_alias::v3::Response> {
let request = get_alias::v3::Request::new(room_alias.to_owned());
self.send(request, None).await
}
/// Gets the homeserver’s supported login types.
///
/// This should be the first step when trying to login so you can call the
/// appropriate method for the next step.
pub async fn get_login_types(&self) -> HttpResult<get_login_types::v3::Response> {
let request = get_login_types::v3::Request::new();
self.send(request, None).await
}
/// Get the URL to use to login via Single Sign-On.
///
/// Returns a URL that should be opened in a web browser to let the user
/// login.
///
/// After a successful login, the loginToken received at the redirect URL
/// should be used to login with [`login_with_token`].
///
/// # Arguments
///
/// * `redirect_url` - The URL that will receive a `loginToken` after a
/// successful SSO login.
///
/// * `idp_id` - The optional ID of the identity provider to login with.
///
/// [`login_with_token`]: #method.login_with_token
pub async fn get_sso_login_url(
&self,
redirect_url: &str,
idp_id: Option<&str>,
) -> Result<String> {
let homeserver = self.homeserver().await;
let server_versions = self.server_versions().await?;
let request = if let Some(id) = idp_id {
sso_login_with_provider::v3::Request::new(id.to_owned(), redirect_url.to_owned())
.try_into_http_request::<Vec<u8>>(
homeserver.as_str(),
SendAccessToken::None,
server_versions,
)
} else {
sso_login::v3::Request::new(redirect_url.to_owned()).try_into_http_request::<Vec<u8>>(
homeserver.as_str(),
SendAccessToken::None,
server_versions,
)
};
match request {
Ok(req) => Ok(req.uri().to_string()),
Err(err) => Err(Error::from(HttpError::from(err))),
}
}
/// Login to the server with a username and password.
///
/// This can be used for the first login as well as for subsequent logins,
/// note that if the device ID isn't provided a new device will be created.
///
/// If this isn't the first login, a device ID should be provided through
/// [`LoginBuilder::device_id`] to restore the correct stores.
///
/// Alternatively the [`restore_session`] method can be used to restore a
/// logged-in client without the password.
///
/// # Arguments
///
/// * `user` - The user ID or user ID localpart of the user that should be
/// logged into the homeserver.
///
/// * `password` - The password of the user.
///
/// # Example
///
/// ```no_run
/// # use futures::executor::block_on;
/// # use url::Url;
/// # let homeserver = Url::parse("http://example.com").unwrap();
/// # block_on(async {
/// use matrix_sdk::Client;
///
/// let client = Client::new(homeserver).await?;
/// let user = "example";
///
/// let response = client
/// .login_username(user, "wordpass")
/// .initial_device_display_name("My bot")
/// .await?;
///
/// println!(
/// "Logged in as {user}, got device_id {} and access_token {}",