src/server.rs
945 lines · 29891 bytes
1//! Matrix server abstraction.
2//!
3//! A MatrixServer is created for every server the user configures.
4//!
5//! It will create a per server config subsection. If options are added to the
6//! server they need to be removed from the server section when the server is
7//! dropped.
8//!
9//! The server will create a tokio runtime which will spawn a task for the sync
10//! loop.
11//!
12//! It will also spawn a task on the Weechat mainloop, this one waits for
13//! responses from the sync loop.
14//!
15//! A separate task is spawned every time Weechat wants to send a message to the
16//! server.
17//!
18//!
19//! Schematically this looks like the following diagram.
20//!
21//! MatrixServer
22//! +--------------------------------------------------------------------+
23//! | |
24//! | Weechat mainloop Tokio runtime |
25//! | +---------------------------+ +------------------------+ |
26//! | | | | | |
27//! | | +--------------------+ | | +----------------+ | |
28//! | | | | | | | | | |
29//! | | | Response receiver +<---------------+ Sync loop | | |
30//! | | | | | | | | | |
31//! | | | | | | | | | |
32//! | | +--------------------+ | | +----------------+ | |
33//! | | | | | |
34//! | | +--------------------+ | | +----------------+ | |
35//! | | | | | Spawn | | | | |
36//! | | | Roombuffer input +--------------->+ Send coroutine | | |
37//! | | | callback +<---------------+ | | |
38//! | | | | | | | | | |
39//! | | +--------------------+ | | +----------------+ | |
40//! | | | | | |
41//! | +---------------------------+ +------------------------+ |
42//! | |
43//! +--------------------------------------------------------------------+
44//!
45//!
46//! The tokio runtime and response receiver task will be alive only if the user
47//! connects to the server while the room buffer input callback will print an
48//! error if the server is disconnected.
49//!
50//! The server holds all the rooms which in turn hold the buffers, users, and
51//! room metadata.
52//!
53//! The response receiver forwards events to the correct room. The response
54//! receiver fetches events individually from a mpsc channel. This makes sure
55//! that processing events will not block the Weechat mainloop for too long.
56
57use chrono::{offset::Utc, DateTime};
58use indoc::indoc;
59use std::{
60 cell::{Ref, RefCell, RefMut},
61 collections::HashMap,
62 path::PathBuf,
63 rc::{Rc, Weak},
64};
65use tracing::error;
66use url::Url;
67
68use matrix_sdk::{
69 self,
70 api::r0::{
71 membership::get_member_events::Response as MembersResponse,
72 session::login::Response as LoginResponse,
73 },
74 events::{AnySyncRoomEvent, AnySyncStateEvent},
75 identifiers::{DeviceIdBox, RoomId, UserId},
76 Client, ClientConfig, Room,
77};
78
79use weechat::{
80 buffer::{BufferBuilder, BufferHandle},
81 config::{BooleanOptionSettings, ConfigSection, StringOptionSettings},
82 Prefix, Weechat,
83};
84
85use crate::{
86 config::Config,
87 connection::{Connection, InteractiveAuthInfo},
88 room::RoomHandle,
89 ConfigHandle, PLUGIN_NAME,
90};
91
92#[derive(Debug)]
93pub enum ServerError {
94 StartError(String),
95 IoError(String),
96}
97
98#[derive(Clone, Debug, PartialEq)]
99pub struct ServerSettings {
100 pub homeserver: Option<Url>,
101 pub proxy: Option<Url>,
102 pub autoconnect: bool,
103 pub username: String,
104 pub password: String,
105 pub ssl_verify: bool,
106}
107
108impl Default for ServerSettings {
109 fn default() -> Self {
110 Self {
111 ssl_verify: true,
112 proxy: None,
113 autoconnect: false,
114 homeserver: None,
115 username: "".to_owned(),
116 password: "".to_owned(),
117 }
118 }
119}
120
121impl ServerSettings {
122 pub fn new() -> Self {
123 Default::default()
124 }
125}
126
127pub struct LoginInfo {
128 user_id: UserId,
129}
130
131#[derive(Clone)]
132pub struct MatrixServer {
133 #[allow(clippy::rc_buffer)]
134 server_name: Rc<String>,
135 inner: Rc<RefCell<InnerServer>>,
136}
137
138impl std::fmt::Debug for MatrixServer {
139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140 let mut fmt = f.debug_struct("MatrixServer");
141 fmt.field("name", &self.server_name).finish()
142 }
143}
144
145pub struct InnerServer {
146 #[allow(clippy::rc_buffer)]
147 server_name: Rc<String>,
148 rooms: HashMap<RoomId, RoomHandle>,
149 settings: ServerSettings,
150 current_settings: ServerSettings,
151 config: ConfigHandle,
152 client: Option<Client>,
153 login_state: Option<LoginInfo>,
154 connection: Rc<RefCell<Option<Connection>>>,
155 server_buffer: Rc<RefCell<Option<BufferHandle>>>,
156}
157
158impl MatrixServer {
159 pub fn new(
160 name: &str,
161 config: &ConfigHandle,
162 server_section: &mut ConfigSection,
163 ) -> Self {
164 let server_name = Rc::new(name.to_owned());
165
166 let server = InnerServer {
167 server_name: server_name.clone(),
168 rooms: HashMap::new(),
169 settings: ServerSettings::new(),
170 current_settings: ServerSettings::new(),
171 config: config.clone(),
172 client: None,
173 login_state: None,
174 connection: Rc::new(RefCell::new(None)),
175 server_buffer: Rc::new(RefCell::new(None)),
176 };
177
178 let server = Rc::new(RefCell::new(server));
179 MatrixServer::create_server_conf(&server_name, server_section, &server);
180
181 MatrixServer {
182 server_name,
183 inner: server,
184 }
185 }
186
187 pub fn name(&self) -> &str {
188 &self.server_name
189 }
190
191 pub fn inner(&self) -> Ref<'_, InnerServer> {
192 self.inner.borrow()
193 }
194
195 pub fn config(&self) -> ConfigHandle {
196 self.inner().config.clone()
197 }
198
199 pub fn clone_inner_weak(&self) -> Weak<RefCell<InnerServer>> {
200 Rc::downgrade(&self.inner)
201 }
202
203 pub fn connection(&self) -> Option<Connection> {
204 self.inner().connection.borrow().clone()
205 }
206
207 pub async fn delete_devices(&self, devices: Vec<DeviceIdBox>) {
208 let formatted = devices
209 .iter()
210 .map(|d| d.to_string())
211 .collect::<Vec<String>>()
212 .join(", ");
213
214 let print_success = || {
215 self.print_network(&format!(
216 "Successfully deleted device(s) {}",
217 formatted
218 ));
219 };
220
221 let print_fail = |e| {
222 self.print_error(&format!(
223 "Error deleting device(s) {} {:#?}",
224 formatted, e
225 ));
226 };
227
228 if let Some(c) = self.connection() {
229 match c.delete_devices(devices.clone(), None).await {
230 Ok(_) => print_success(),
231 Err(e) => {
232 if let Some(info) = e.uiaa_response() {
233 let auth_info = InteractiveAuthInfo {
234 user: self.inner().settings().username.clone(),
235 password: self.inner().settings().password.clone(),
236 session: info.session.clone(),
237 };
238
239 if let Err(e) = c
240 .delete_devices(devices.clone(), Some(auth_info))
241 .await
242 {
243 print_fail(e);
244 } else {
245 print_success();
246 }
247 } else {
248 print_fail(e)
249 }
250 }
251 }
252 };
253 }
254
255 pub async fn export_keys(&self, file: PathBuf, passphrase: String) {
256 let client = self.inner().get_client().unwrap();
257
258 let export = async move {
259 client.export_keys(file, &passphrase, |_| true).await
260 };
261
262 if let Some(c) = self.connection() {
263 if let Err(e) = c.spawn(export).await {
264 self.print_error(&format!(
265 "Error exporting E2EE keys {:#?}",
266 e
267 ));
268 } else {
269 self.print_network("Sucessfully exported E2EE keys")
270 }
271 };
272 }
273
274 pub async fn import_keys(&self, file: PathBuf, passphrase: String) {
275 let client = self.inner().get_client().unwrap();
276
277 if let Some(c) = self.connection() {
278 self.print_network(&format!(
279 "Importing E2EE keys from {}, this may take a while..",
280 file.display()
281 ));
282 let import =
283 async move { client.import_keys(file, &passphrase).await };
284
285 match c.spawn(import).await {
286 Ok((imported, total)) => {
287 if imported > 0 {
288 self.print_network(&format!(
289 "Sucessfully imported {} E2EE keys",
290 imported
291 ));
292 } else if total > 0 {
293 self.print_network(
294 "No keys were imported, the key export contains only \
295 keys that we already have",
296 );
297 } else {
298 self.print_network(
299 "No keys were imported, either the key export is empty"
300 );
301 }
302 }
303 Err(e) => {
304 self.print_error(&format!(
305 "Error importing E2EE keys {:#?}",
306 e
307 ));
308 }
309 }
310 };
311 }
312
313 pub async fn devices(&self) {
314 if let Some(c) = self.connection() {
315 let response = match c.devices().await {
316 Ok(r) => r,
317 Err(e) => {
318 self.print_error(&format!(
319 "Error fetching devices {:?}",
320 e
321 ));
322 return;
323 }
324 };
325
326 if response.devices.is_empty() {
327 self.print_error("No devices were found for this server");
328 return;
329 }
330
331 self.print_network(&format!(
332 indoc!(
333 "
334 Devices for server {}{}{}:
335 Device ID Device name Last seen
336 "
337 ),
338 Weechat::color("chat_server"),
339 self.name(),
340 Weechat::color("reset")
341 ));
342
343 let lines: Vec<String> = response
344 .devices
345 .iter()
346 .map(|d| {
347 let device_color = Weechat::info_get(
348 "nick_color_name",
349 d.device_id.as_str(),
350 )
351 .expect("Can't get device color");
352
353 let last_seen_date =
354 d.last_seen_ts.map_or("?".to_owned(), |d| {
355 let date: DateTime<Utc> = d.into();
356 date.format("%Y/%m/%d %H:%M").to_string()
357 });
358
359 let last_seen = format!(
360 "{} @ {}",
361 d.last_seen_ip.as_deref().unwrap_or("-"),
362 last_seen_date
363 );
364
365 format!(
366 " {}{:<15}{}{:<30}{:<}",
367 Weechat::color(&device_color),
368 d.device_id.as_str(),
369 Weechat::color("reset"),
370 d.display_name.as_deref().unwrap_or(""),
371 last_seen,
372 )
373 })
374 .collect();
375
376 let line = lines.join("\n");
377 self.print_network(&line);
378 };
379 }
380
381 /// Parse an URL returning a None if the string is empty.
382 ///
383 /// # Panics
384 ///
385 /// This panics if the string can't be parsed as an URL.
386 fn parse_url_unchecked(value: &str) -> Option<Url> {
387 if value.is_empty() {
388 None
389 } else {
390 Some(
391 Url::parse(value)
392 .expect("Can't parse URL, did the check callback fail?"),
393 )
394 }
395 }
396
397 /// Parse an URL returning an error if the parse step fails.
398 pub fn parse_url(value: String) -> Result<(), String> {
399 let url = Url::parse(&value);
400
401 match url {
402 Ok(u) => {
403 if u.cannot_be_a_base() {
404 Err(String::from("The Homeserver URL is missing a schema"))
405 } else {
406 Ok(())
407 }
408 }
409 Err(e) => Err(e.to_string()),
410 }
411 }
412
413 /// Check if the provided value is a valid URL.
414 fn is_url_valid(value: &str) -> bool {
415 if value.is_empty() {
416 true
417 } else {
418 MatrixServer::parse_url(value.to_string()).is_ok()
419 }
420 }
421
422 fn create_server_conf(
423 server_name: &str,
424 server_section: &mut ConfigSection,
425 server_ref: &Rc<RefCell<InnerServer>>,
426 ) {
427 let server = Rc::downgrade(server_ref);
428 let server_copy = server.clone();
429 let autoconnect =
430 BooleanOptionSettings::new(format!("{}.autoconnect", server_name))
431 .set_change_callback(move |_, option| {
432 let value = option.value();
433
434 let server_ref = server.upgrade().expect(
435 "Server got deleted while server config is alive",
436 );
437
438 let mut server = server_ref.borrow_mut();
439 server.settings.autoconnect = value;
440 });
441
442 server_section
443 .new_boolean_option(autoconnect)
444 .expect("Can't create autoconnect option");
445
446 let server = server_copy;
447 let server_copy = server.clone();
448
449 let homeserver =
450 StringOptionSettings::new(format!("{}.homeserver", server_name))
451 .set_check_callback(|_, _, value| {
452 MatrixServer::is_url_valid(&value)
453 })
454 .set_change_callback(move |_, option| {
455 let server_ref = server.upgrade().expect(
456 "Server got deleted while server config is alive",
457 );
458
459 let mut server = server_ref.borrow_mut();
460
461 server.settings.homeserver =
462 MatrixServer::parse_url_unchecked(&option.value());
463 });
464
465 server_section
466 .new_string_option(homeserver)
467 .expect("Can't create homeserver option");
468
469 let server = server_copy;
470 let server_copy = server.clone();
471
472 let proxy = StringOptionSettings::new(format!("{}.proxy", server_name))
473 .set_check_callback(|_, _, value| {
474 MatrixServer::is_url_valid(&value)
475 })
476 .set_change_callback(move |_, option| {
477 let server_ref = server
478 .upgrade()
479 .expect("Server got deleted while server config is alive");
480
481 let mut server = server_ref.borrow_mut();
482 server.settings.proxy =
483 MatrixServer::parse_url_unchecked(&option.value());
484 });
485
486 server_section
487 .new_string_option(proxy)
488 .expect("Can't create proxy option");
489
490 let server = server_copy;
491 let server_copy = server.clone();
492
493 let username =
494 StringOptionSettings::new(format!("{}.username", server_name))
495 .set_change_callback(move |_, option| {
496 let server_ref = server.upgrade().expect(
497 "Server got deleted while server config is alive",
498 );
499
500 let mut server = server_ref.borrow_mut();
501 server.settings.username = option.value().to_string();
502 });
503
504 server_section
505 .new_string_option(username)
506 .expect("Can't create username option");
507
508 let server = server_copy;
509 let server_copy = server.clone();
510
511 let password =
512 StringOptionSettings::new(format!("{}.password", server_name))
513 .set_change_callback(move |_, option| {
514 let server_ref = server.upgrade().expect(
515 "Server got deleted while server config is alive",
516 );
517
518 let mut server = server_ref.borrow_mut();
519 server.settings.password = option.value().to_string();
520 });
521
522 server_section
523 .new_string_option(password)
524 .expect("Can't create password option");
525
526 let server = server_copy;
527
528 let ssl_verify =
529 BooleanOptionSettings::new(format!("{}.ssl_verify", server_name))
530 .default_value(true)
531 .set_change_callback(move |_, option| {
532 let value = option.value();
533
534 let server_ref = server.upgrade().expect(
535 "Server got deleted while server config is alive",
536 );
537
538 let mut server = server_ref.borrow_mut();
539 server.settings.ssl_verify = value;
540 });
541
542 server_section
543 .new_boolean_option(ssl_verify)
544 .expect("Can't create autoconnect option");
545 }
546
547 pub fn connected(&self) -> bool {
548 self.inner.borrow().connected()
549 }
550
551 pub fn autoconnect(&self) -> bool {
552 self.inner.borrow().settings.autoconnect
553 }
554
555 pub fn is_connection_secure(&self) -> bool {
556 self.inner.borrow().current_settings.ssl_verify
557 && self
558 .inner
559 .borrow()
560 .current_settings
561 .homeserver
562 .as_ref()
563 .map(|u| u.scheme() == "https")
564 .unwrap_or(false)
565 }
566
567 pub fn connect(&self) -> Result<(), ServerError> {
568 if self.connected() {
569 self.print_error(&format!(
570 "Already connected to {}{}{}",
571 Weechat::color("chat_server"),
572 self.name(),
573 Weechat::color("reset")
574 ));
575
576 return Ok(());
577 }
578
579 let client = self.inner.borrow_mut().get_or_create_client()?;
580 let connection = Connection::new(&self, &client);
581
582 *self.inner.borrow_mut().connection.borrow_mut() = Some(connection);
583
584 self.print_network(&format!(
585 "Connected to {}{}{}",
586 Weechat::color("chat_server"),
587 self.name(),
588 Weechat::color("reset")
589 ));
590
591 Ok(())
592 }
593
594 pub fn print(&self, message: &str) {
595 self.inner().print(message)
596 }
597
598 pub fn print_with_prefix(&self, prefix: &str, message: &str) {
599 self.inner().print_with_prefix(prefix, message)
600 }
601
602 pub fn print_network(&self, message: &str) {
603 self.inner().print_network(message)
604 }
605
606 pub fn print_error(&self, message: &str) {
607 self.inner().print_error(message)
608 }
609
610 pub fn disconnect(&self) {
611 if !self.connected() {
612 self.print_error(&format!(
613 "Not connected to {}{}{}",
614 Weechat::color("chat_server"),
615 self.name(),
616 Weechat::color("reset")
617 ));
618
619 return;
620 }
621
622 {
623 let server = self.inner();
624 let mut connection = server.connection.borrow_mut();
625 connection.take();
626 }
627
628 self.print_network(&format!(
629 "Disconnected from {}{}{}",
630 Weechat::color("chat_server"),
631 self.name(),
632 Weechat::color("reset")
633 ));
634 }
635
636 pub fn get_info_str(&self, details: bool) -> String {
637 let mut s = String::from(&format!(
638 "{}{}{} [{}]",
639 Weechat::color("chat_server"),
640 self.server_name.as_ref().to_owned(),
641 Weechat::color("reset"),
642 if self.connected() {
643 "connected"
644 } else {
645 "not connected"
646 }
647 ));
648
649 if !details {
650 return s;
651 }
652
653 let settings = &self.inner.borrow().settings;
654 s.push_str(&format!(
655 "\n\
656 {:indent$}homeserver: {}\n\
657 {:indent$}proxy: {}\n\
658 {:indent$}autoconnect: {}\n\
659 {:indent$}username: {}\n",
660 "",
661 settings.homeserver.as_ref().map_or("", |url| url.as_str()),
662 "",
663 settings.proxy.as_ref().map_or("", |url| url.as_str()),
664 "",
665 settings.autoconnect,
666 "",
667 settings.username,
668 indent = 8
669 ));
670 s
671 }
672}
673
674impl Drop for InnerServer {
675 fn drop(&mut self) {
676 // TODO close all the server buffers.
677 let config = &self.config;
678 let mut config_borrow = config.borrow_mut();
679
680 let mut section = config_borrow
681 .search_section_mut("server")
682 .expect("Can't get server section");
683
684 for option_name in
685 &["homeserver", "autoconnect", "password", "proxy", "username"]
686 {
687 let option_name = &format!("{}.{}", self.server_name, option_name);
688 section.free_option(option_name).unwrap_or_else(|_| {
689 panic!(format!("Can't free option {}", option_name))
690 });
691 }
692 }
693}
694
695impl InnerServer {
696 pub(crate) fn get_or_create_room(
697 &mut self,
698 room_id: &RoomId,
699 ) -> &RoomHandle {
700 if !self.rooms.contains_key(room_id) {
701 let homeserver = self
702 .settings
703 .homeserver
704 .as_ref()
705 .expect("Creating room buffer while no homeserver");
706 let login_state = self
707 .login_state
708 .as_ref()
709 .expect("Receiving events while not being logged in");
710 let room = self
711 .client
712 .as_ref()
713 .expect("Receiving events without a client")
714 .get_joined_room(room_id);
715
716 let room = room.expect(&format!(
717 "Receiving events for a room while no room found {}",
718 room_id
719 ));
720 let buffer = RoomHandle::new(
721 &self.server_name,
722 &self.connection,
723 self.config.inner.clone(),
724 room,
725 homeserver,
726 room_id.clone(),
727 &login_state.user_id,
728 );
729 self.rooms.insert(room_id.clone(), buffer);
730 }
731
732 self.rooms.get_mut(room_id).unwrap()
733 }
734
735 pub fn settings(&self) -> &ServerSettings {
736 &self.settings
737 }
738
739 pub fn rooms(&self) -> &HashMap<RoomId, RoomHandle> {
740 &self.rooms
741 }
742
743 pub fn config(&self) -> Ref<Config> {
744 self.config.borrow()
745 }
746
747 pub async fn restore_room(&mut self, _room: Room) {
748 // let homeserver = self
749 // .settings
750 // .homeserver
751 // .as_ref()
752 // .expect("Creating room buffer while no homeserver");
753
754 // let buffer = RoomHandle::restore(
755 // room,
756 // &self.connection,
757 // self.config.inner.clone(),
758 // homeserver,
759 // )
760 // .await;
761 // let room_id = buffer.room_id().to_owned();
762
763 // self.rooms.insert(room_id, buffer);
764 }
765
766 fn create_server_buffer(&self) -> BufferHandle {
767 let buffer_handle =
768 BufferBuilder::new(&format!("server.{}", self.server_name))
769 .build()
770 .expect("Can't create Matrix debug buffer");
771
772 let buffer = buffer_handle
773 .upgrade()
774 .expect("Can't upgrade newly created server buffer");
775
776 buffer.set_short_name(&self.server_name);
777 buffer.set_localvar("type", "server");
778 buffer.set_localvar("nick", &self.settings.username);
779 buffer.set_localvar("server", &self.server_name);
780
781 buffer_handle
782 }
783
784 fn get_client(&self) -> Option<Client> {
785 self.client.clone()
786 }
787
788 fn get_or_create_client(&mut self) -> Result<Client, ServerError> {
789 let client = if let Some(c) = self.client.as_ref() {
790 c.clone()
791 } else {
792 self.create_client()?
793 };
794
795 // Check if the homeserver setting changed and swap our client if it
796 // did.
797 if self.current_settings != self.settings {
798 // TODO if the homeserver changed close all the room buffers of the
799 // server here, they don't belong to our client anymore.
800 self.create_client()
801 } else {
802 Ok(client)
803 }
804 }
805
806 /// Borrow the server buffer handle.
807 pub fn server_buffer(&self) -> Ref<Option<BufferHandle>> {
808 self.server_buffer.borrow()
809 }
810
811 fn get_or_create_buffer<'a>(
812 &self,
813 server_buffer: &'a mut RefMut<Option<BufferHandle>>,
814 ) -> &'a BufferHandle {
815 if let Some(buffer) = server_buffer.as_ref() {
816 if buffer.upgrade().is_err() {
817 let buffer = self.create_server_buffer();
818 **server_buffer = Some(buffer);
819 }
820 } else {
821 let buffer = self.create_server_buffer();
822 **server_buffer = Some(buffer);
823 }
824
825 server_buffer.as_ref().unwrap()
826 }
827
828 /// Print a neutral message to the server buffer.
829 fn print(&self, message: &str) {
830 let mut server_buffer = self.server_buffer.borrow_mut();
831 let buffer = self
832 .get_or_create_buffer(&mut server_buffer)
833 .upgrade()
834 .unwrap();
835 buffer.print(message);
836 }
837
838 /// Print a message with a given prefix to the server buffer.
839 pub fn print_with_prefix(&self, prefix: &str, message: &str) {
840 self.print(&format!("{}{}: {}", prefix, PLUGIN_NAME, message));
841 }
842
843 /// Print an network message to the server buffer.
844 pub fn print_network(&self, message: &str) {
845 self.print_with_prefix(&Weechat::prefix(Prefix::Network), message);
846 }
847
848 /// Print an error message to the server buffer.
849 pub fn print_error(&self, message: &str) {
850 self.print_with_prefix(&Weechat::prefix(Prefix::Error), message);
851 }
852
853 /// Is the server connected.
854 pub fn connected(&self) -> bool {
855 self.connection.borrow().is_some()
856 }
857
858 pub async fn receive_members(
859 &self,
860 room_id: &RoomId,
861 members: MembersResponse,
862 ) {
863 if let Some(room) = self.rooms.get(room_id) {
864 for event in members.chunk {
865 if let Ok(member) = event.deserialize() {
866 room.handle_membership_event(&member.into(), true).await;
867 }
868 }
869 } else {
870 error!("ROOM WITH ID {} NOT FOUND", room_id);
871 }
872 }
873
874 pub async fn receive_joined_state_event(
875 &mut self,
876 room_id: &RoomId,
877 event: AnySyncStateEvent,
878 ) {
879 let room = self.get_or_create_room(room_id);
880 room.handle_sync_state_event(&event, true).await
881 }
882
883 pub async fn receive_joined_timeline_event(
884 &mut self,
885 room_id: &RoomId,
886 event: AnySyncRoomEvent,
887 ) {
888 let room = self.get_or_create_room(room_id);
889 room.handle_sync_room_event(event).await
890 }
891
892 pub fn receive_login(&mut self, response: LoginResponse) {
893 let login_state = LoginInfo {
894 user_id: response.user_id,
895 };
896 self.login_state = Some(login_state);
897 }
898
899 fn create_server_dir(&self) -> std::io::Result<()> {
900 let path = self.get_server_path();
901 std::fs::create_dir_all(path)
902 }
903
904 pub fn get_server_path(&self) -> PathBuf {
905 let mut path = Weechat::home_dir();
906 let server_name: &str = &self.server_name;
907 path.push("matrix-rust");
908 path.push(server_name);
909
910 path
911 }
912
913 pub fn create_client(&mut self) -> Result<Client, ServerError> {
914 let settings = self.settings.clone();
915
916 let homeserver = settings.homeserver.as_ref().ok_or_else(|| {
917 ServerError::StartError("Homeserver not configured".to_owned())
918 })?;
919
920 self.create_server_dir().map_err(|e| {
921 ServerError::IoError(format!(
922 "Error creating the session dir: {}",
923 e
924 ))
925 })?;
926
927 let mut client_config =
928 ClientConfig::new().store_path(self.get_server_path());
929
930 if let Some(proxy) = settings.proxy.as_ref() {
931 client_config = client_config.proxy(proxy.as_str()).unwrap();
932 }
933
934 if !settings.ssl_verify {
935 client_config = client_config.disable_ssl_verification();
936 }
937
938 let client =
939 Client::new_with_config(homeserver.clone(), client_config).unwrap();
940 self.current_settings = settings;
941 self.client = Some(client.clone());
942
943 Ok(client)
944 }
945}