src/server.rs
941 lines · 29805 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 clone_inner_weak(&self) -> Weak<RefCell<InnerServer>> {
196 Rc::downgrade(&self.inner)
197 }
198
199 pub fn connection(&self) -> Option<Connection> {
200 self.inner().connection.borrow().clone()
201 }
202
203 pub async fn delete_devices(&self, devices: Vec<DeviceIdBox>) {
204 let formatted = devices
205 .iter()
206 .map(|d| d.to_string())
207 .collect::<Vec<String>>()
208 .join(", ");
209
210 let print_success = || {
211 self.print_network(&format!(
212 "Successfully deleted device(s) {}",
213 formatted
214 ));
215 };
216
217 let print_fail = |e| {
218 self.print_error(&format!(
219 "Error deleting device(s) {} {:#?}",
220 formatted, e
221 ));
222 };
223
224 if let Some(c) = self.connection() {
225 match c.delete_devices(devices.clone(), None).await {
226 Ok(_) => print_success(),
227 Err(e) => {
228 if let Some(info) = e.uiaa_response() {
229 let auth_info = InteractiveAuthInfo {
230 user: self.inner().settings().username.clone(),
231 password: self.inner().settings().password.clone(),
232 session: info.session.clone(),
233 };
234
235 if let Err(e) = c
236 .delete_devices(devices.clone(), Some(auth_info))
237 .await
238 {
239 print_fail(e);
240 } else {
241 print_success();
242 }
243 } else {
244 print_fail(e)
245 }
246 }
247 }
248 };
249 }
250
251 pub async fn export_keys(&self, file: PathBuf, passphrase: String) {
252 let client = self.inner().get_client().unwrap();
253
254 let export = async move {
255 client.export_keys(file, &passphrase, |_| true).await
256 };
257
258 if let Some(c) = self.connection() {
259 if let Err(e) = c.spawn(export).await {
260 self.print_error(&format!(
261 "Error exporting E2EE keys {:#?}",
262 e
263 ));
264 } else {
265 self.print_network("Sucessfully exported E2EE keys")
266 }
267 };
268 }
269
270 pub async fn import_keys(&self, file: PathBuf, passphrase: String) {
271 let client = self.inner().get_client().unwrap();
272
273 if let Some(c) = self.connection() {
274 self.print_network(&format!(
275 "Importing E2EE keys from {}, this may take a while..",
276 file.display()
277 ));
278 let import =
279 async move { client.import_keys(file, &passphrase).await };
280
281 match c.spawn(import).await {
282 Ok((imported, total)) => {
283 if imported > 0 {
284 self.print_network(&format!(
285 "Sucessfully imported {} E2EE keys",
286 imported
287 ));
288 } else if total > 0 {
289 self.print_network(
290 "No keys were imported, the key export contains only \
291 keys that we already have",
292 );
293 } else {
294 self.print_network(
295 "No keys were imported, either the key export is empty"
296 );
297 }
298 }
299 Err(e) => {
300 self.print_error(&format!(
301 "Error importing E2EE keys {:#?}",
302 e
303 ));
304 }
305 }
306 };
307 }
308
309 pub async fn devices(&self) {
310 if let Some(c) = self.connection() {
311 let response = match c.devices().await {
312 Ok(r) => r,
313 Err(e) => {
314 self.print_error(&format!(
315 "Error fetching devices {:?}",
316 e
317 ));
318 return;
319 }
320 };
321
322 if response.devices.is_empty() {
323 self.print_error("No devices were found for this server");
324 return;
325 }
326
327 self.print_network(&format!(
328 indoc!(
329 "
330 Devices for server {}{}{}:
331 Device ID Device name Last seen
332 "
333 ),
334 Weechat::color("chat_server"),
335 self.name(),
336 Weechat::color("reset")
337 ));
338
339 let lines: Vec<String> = response
340 .devices
341 .iter()
342 .map(|d| {
343 let device_color = Weechat::info_get(
344 "nick_color_name",
345 d.device_id.as_str(),
346 )
347 .expect("Can't get device color");
348
349 let last_seen_date =
350 d.last_seen_ts.map_or("?".to_owned(), |d| {
351 let date: DateTime<Utc> = d.into();
352 date.format("%Y/%m/%d %H:%M").to_string()
353 });
354
355 let last_seen = format!(
356 "{} @ {}",
357 d.last_seen_ip.as_deref().unwrap_or("-"),
358 last_seen_date
359 );
360
361 format!(
362 " {}{:<15}{}{:<30}{:<}",
363 Weechat::color(&device_color),
364 d.device_id.as_str(),
365 Weechat::color("reset"),
366 d.display_name.as_deref().unwrap_or(""),
367 last_seen,
368 )
369 })
370 .collect();
371
372 let line = lines.join("\n");
373 self.print_network(&line);
374 };
375 }
376
377 /// Parse an URL returning a None if the string is empty.
378 ///
379 /// # Panics
380 ///
381 /// This panics if the string can't be parsed as an URL.
382 fn parse_url_unchecked(value: &str) -> Option<Url> {
383 if value.is_empty() {
384 None
385 } else {
386 Some(
387 Url::parse(value)
388 .expect("Can't parse URL, did the check callback fail?"),
389 )
390 }
391 }
392
393 /// Parse an URL returning an error if the parse step fails.
394 pub fn parse_url(value: String) -> Result<(), String> {
395 let url = Url::parse(&value);
396
397 match url {
398 Ok(u) => {
399 if u.cannot_be_a_base() {
400 Err(String::from("The Homeserver URL is missing a schema"))
401 } else {
402 Ok(())
403 }
404 }
405 Err(e) => Err(e.to_string()),
406 }
407 }
408
409 /// Check if the provided value is a valid URL.
410 fn is_url_valid(value: &str) -> bool {
411 if value.is_empty() {
412 true
413 } else {
414 MatrixServer::parse_url(value.to_string()).is_ok()
415 }
416 }
417
418 fn create_server_conf(
419 server_name: &str,
420 server_section: &mut ConfigSection,
421 server_ref: &Rc<RefCell<InnerServer>>,
422 ) {
423 let server = Rc::downgrade(server_ref);
424 let server_copy = server.clone();
425 let autoconnect =
426 BooleanOptionSettings::new(format!("{}.autoconnect", server_name))
427 .set_change_callback(move |_, option| {
428 let value = option.value();
429
430 let server_ref = server.upgrade().expect(
431 "Server got deleted while server config is alive",
432 );
433
434 let mut server = server_ref.borrow_mut();
435 server.settings.autoconnect = value;
436 });
437
438 server_section
439 .new_boolean_option(autoconnect)
440 .expect("Can't create autoconnect option");
441
442 let server = server_copy;
443 let server_copy = server.clone();
444
445 let homeserver =
446 StringOptionSettings::new(format!("{}.homeserver", server_name))
447 .set_check_callback(|_, _, value| {
448 MatrixServer::is_url_valid(&value)
449 })
450 .set_change_callback(move |_, option| {
451 let server_ref = server.upgrade().expect(
452 "Server got deleted while server config is alive",
453 );
454
455 let mut server = server_ref.borrow_mut();
456
457 server.settings.homeserver =
458 MatrixServer::parse_url_unchecked(&option.value());
459 });
460
461 server_section
462 .new_string_option(homeserver)
463 .expect("Can't create homeserver option");
464
465 let server = server_copy;
466 let server_copy = server.clone();
467
468 let proxy = StringOptionSettings::new(format!("{}.proxy", server_name))
469 .set_check_callback(|_, _, value| {
470 MatrixServer::is_url_valid(&value)
471 })
472 .set_change_callback(move |_, option| {
473 let server_ref = server
474 .upgrade()
475 .expect("Server got deleted while server config is alive");
476
477 let mut server = server_ref.borrow_mut();
478 server.settings.proxy =
479 MatrixServer::parse_url_unchecked(&option.value());
480 });
481
482 server_section
483 .new_string_option(proxy)
484 .expect("Can't create proxy option");
485
486 let server = server_copy;
487 let server_copy = server.clone();
488
489 let username =
490 StringOptionSettings::new(format!("{}.username", server_name))
491 .set_change_callback(move |_, option| {
492 let server_ref = server.upgrade().expect(
493 "Server got deleted while server config is alive",
494 );
495
496 let mut server = server_ref.borrow_mut();
497 server.settings.username = option.value().to_string();
498 });
499
500 server_section
501 .new_string_option(username)
502 .expect("Can't create username option");
503
504 let server = server_copy;
505 let server_copy = server.clone();
506
507 let password =
508 StringOptionSettings::new(format!("{}.password", server_name))
509 .set_change_callback(move |_, option| {
510 let server_ref = server.upgrade().expect(
511 "Server got deleted while server config is alive",
512 );
513
514 let mut server = server_ref.borrow_mut();
515 server.settings.password = option.value().to_string();
516 });
517
518 server_section
519 .new_string_option(password)
520 .expect("Can't create password option");
521
522 let server = server_copy;
523
524 let ssl_verify =
525 BooleanOptionSettings::new(format!("{}.ssl_verify", server_name))
526 .default_value(true)
527 .set_change_callback(move |_, option| {
528 let value = option.value();
529
530 let server_ref = server.upgrade().expect(
531 "Server got deleted while server config is alive",
532 );
533
534 let mut server = server_ref.borrow_mut();
535 server.settings.ssl_verify = value;
536 });
537
538 server_section
539 .new_boolean_option(ssl_verify)
540 .expect("Can't create autoconnect option");
541 }
542
543 pub fn connected(&self) -> bool {
544 self.inner.borrow().connected()
545 }
546
547 pub fn autoconnect(&self) -> bool {
548 self.inner.borrow().settings.autoconnect
549 }
550
551 pub fn is_connection_secure(&self) -> bool {
552 self.inner.borrow().current_settings.ssl_verify
553 && self
554 .inner
555 .borrow()
556 .current_settings
557 .homeserver
558 .as_ref()
559 .map(|u| u.scheme() == "https")
560 .unwrap_or(false)
561 }
562
563 pub fn connect(&self) -> Result<(), ServerError> {
564 if self.connected() {
565 self.print_error(&format!(
566 "Already connected to {}{}{}",
567 Weechat::color("chat_server"),
568 self.name(),
569 Weechat::color("reset")
570 ));
571
572 return Ok(());
573 }
574
575 let client = self.inner.borrow_mut().get_or_create_client()?;
576 let connection = Connection::new(&self, &client);
577
578 *self.inner.borrow_mut().connection.borrow_mut() = Some(connection);
579
580 self.print_network(&format!(
581 "Connected to {}{}{}",
582 Weechat::color("chat_server"),
583 self.name(),
584 Weechat::color("reset")
585 ));
586
587 Ok(())
588 }
589
590 pub fn print(&self, message: &str) {
591 self.inner().print(message)
592 }
593
594 pub fn print_with_prefix(&self, prefix: &str, message: &str) {
595 self.inner().print_with_prefix(prefix, message)
596 }
597
598 pub fn print_network(&self, message: &str) {
599 self.inner().print_network(message)
600 }
601
602 pub fn print_error(&self, message: &str) {
603 self.inner().print_error(message)
604 }
605
606 pub fn disconnect(&self) {
607 if !self.connected() {
608 self.print_error(&format!(
609 "Not connected to {}{}{}",
610 Weechat::color("chat_server"),
611 self.name(),
612 Weechat::color("reset")
613 ));
614
615 return;
616 }
617
618 {
619 let server = self.inner();
620 let mut connection = server.connection.borrow_mut();
621 connection.take();
622 }
623
624 self.print_network(&format!(
625 "Disconnected from {}{}{}",
626 Weechat::color("chat_server"),
627 self.name(),
628 Weechat::color("reset")
629 ));
630 }
631
632 pub fn get_info_str(&self, details: bool) -> String {
633 let mut s = String::from(&format!(
634 "{}{}{} [{}]",
635 Weechat::color("chat_server"),
636 self.server_name.as_ref().to_owned(),
637 Weechat::color("reset"),
638 if self.connected() {
639 "connected"
640 } else {
641 "not connected"
642 }
643 ));
644
645 if !details {
646 return s;
647 }
648
649 let settings = &self.inner.borrow().settings;
650 s.push_str(&format!(
651 "\n\
652 {:indent$}homeserver: {}\n\
653 {:indent$}proxy: {}\n\
654 {:indent$}autoconnect: {}\n\
655 {:indent$}username: {}\n",
656 "",
657 settings.homeserver.as_ref().map_or("", |url| url.as_str()),
658 "",
659 settings.proxy.as_ref().map_or("", |url| url.as_str()),
660 "",
661 settings.autoconnect,
662 "",
663 settings.username,
664 indent = 8
665 ));
666 s
667 }
668}
669
670impl Drop for InnerServer {
671 fn drop(&mut self) {
672 // TODO close all the server buffers.
673 let config = &self.config;
674 let mut config_borrow = config.borrow_mut();
675
676 let mut section = config_borrow
677 .search_section_mut("server")
678 .expect("Can't get server section");
679
680 for option_name in
681 &["homeserver", "autoconnect", "password", "proxy", "username"]
682 {
683 let option_name = &format!("{}.{}", self.server_name, option_name);
684 section.free_option(option_name).unwrap_or_else(|_| {
685 panic!(format!("Can't free option {}", option_name))
686 });
687 }
688 }
689}
690
691impl InnerServer {
692 pub(crate) fn get_or_create_room(
693 &mut self,
694 room_id: &RoomId,
695 ) -> &RoomHandle {
696 if !self.rooms.contains_key(room_id) {
697 let homeserver = self
698 .settings
699 .homeserver
700 .as_ref()
701 .expect("Creating room buffer while no homeserver");
702 let login_state = self
703 .login_state
704 .as_ref()
705 .expect("Receiving events while not being logged in");
706 let room = self
707 .client
708 .as_ref()
709 .expect("Receiving events without a client")
710 .get_joined_room(room_id);
711
712 let room = room.expect(&format!(
713 "Receiving events for a room while no room found {}",
714 room_id
715 ));
716 let buffer = RoomHandle::new(
717 &self.server_name,
718 &self.connection,
719 self.config.inner.clone(),
720 room,
721 homeserver,
722 room_id.clone(),
723 &login_state.user_id,
724 );
725 self.rooms.insert(room_id.clone(), buffer);
726 }
727
728 self.rooms.get_mut(room_id).unwrap()
729 }
730
731 pub fn settings(&self) -> &ServerSettings {
732 &self.settings
733 }
734
735 pub fn rooms(&self) -> &HashMap<RoomId, RoomHandle> {
736 &self.rooms
737 }
738
739 pub fn config(&self) -> Ref<Config> {
740 self.config.borrow()
741 }
742
743 pub async fn restore_room(&mut self, _room: Room) {
744 // let homeserver = self
745 // .settings
746 // .homeserver
747 // .as_ref()
748 // .expect("Creating room buffer while no homeserver");
749
750 // let buffer = RoomHandle::restore(
751 // room,
752 // &self.connection,
753 // self.config.inner.clone(),
754 // homeserver,
755 // )
756 // .await;
757 // let room_id = buffer.room_id().to_owned();
758
759 // self.rooms.insert(room_id, buffer);
760 }
761
762 fn create_server_buffer(&self) -> BufferHandle {
763 let buffer_handle =
764 BufferBuilder::new(&format!("server.{}", self.server_name))
765 .build()
766 .expect("Can't create Matrix debug buffer");
767
768 let buffer = buffer_handle
769 .upgrade()
770 .expect("Can't upgrade newly created server buffer");
771
772 buffer.set_short_name(&self.server_name);
773 buffer.set_localvar("type", "server");
774 buffer.set_localvar("nick", &self.settings.username);
775 buffer.set_localvar("server", &self.server_name);
776
777 buffer_handle
778 }
779
780 fn get_client(&self) -> Option<Client> {
781 self.client.clone()
782 }
783
784 fn get_or_create_client(&mut self) -> Result<Client, ServerError> {
785 let client = if let Some(c) = self.client.as_ref() {
786 c.clone()
787 } else {
788 self.create_client()?
789 };
790
791 // Check if the homeserver setting changed and swap our client if it
792 // did.
793 if self.current_settings != self.settings {
794 // TODO if the homeserver changed close all the room buffers of the
795 // server here, they don't belong to our client anymore.
796 self.create_client()
797 } else {
798 Ok(client)
799 }
800 }
801
802 /// Borrow the server buffer handle.
803 pub fn server_buffer(&self) -> Ref<Option<BufferHandle>> {
804 self.server_buffer.borrow()
805 }
806
807 fn get_or_create_buffer<'a>(
808 &self,
809 server_buffer: &'a mut RefMut<Option<BufferHandle>>,
810 ) -> &'a BufferHandle {
811 if let Some(buffer) = server_buffer.as_ref() {
812 if buffer.upgrade().is_err() {
813 let buffer = self.create_server_buffer();
814 **server_buffer = Some(buffer);
815 }
816 } else {
817 let buffer = self.create_server_buffer();
818 **server_buffer = Some(buffer);
819 }
820
821 server_buffer.as_ref().unwrap()
822 }
823
824 /// Print a neutral message to the server buffer.
825 fn print(&self, message: &str) {
826 let mut server_buffer = self.server_buffer.borrow_mut();
827 let buffer = self
828 .get_or_create_buffer(&mut server_buffer)
829 .upgrade()
830 .unwrap();
831 buffer.print(message);
832 }
833
834 /// Print a message with a given prefix to the server buffer.
835 pub fn print_with_prefix(&self, prefix: &str, message: &str) {
836 self.print(&format!("{}{}: {}", prefix, PLUGIN_NAME, message));
837 }
838
839 /// Print an network message to the server buffer.
840 pub fn print_network(&self, message: &str) {
841 self.print_with_prefix(&Weechat::prefix(Prefix::Network), message);
842 }
843
844 /// Print an error message to the server buffer.
845 pub fn print_error(&self, message: &str) {
846 self.print_with_prefix(&Weechat::prefix(Prefix::Error), message);
847 }
848
849 /// Is the server connected.
850 pub fn connected(&self) -> bool {
851 self.connection.borrow().is_some()
852 }
853
854 pub async fn receive_members(
855 &self,
856 room_id: &RoomId,
857 members: MembersResponse,
858 ) {
859 if let Some(room) = self.rooms.get(room_id) {
860 for event in members.chunk {
861 if let Ok(member) = event.deserialize() {
862 room.handle_membership_event(&member.into(), true).await;
863 }
864 }
865 } else {
866 error!("ROOM WITH ID {} NOT FOUND", room_id);
867 }
868 }
869
870 pub async fn receive_joined_state_event(
871 &mut self,
872 room_id: &RoomId,
873 event: AnySyncStateEvent,
874 ) {
875 let room = self.get_or_create_room(room_id);
876 room.handle_sync_state_event(&event, true).await
877 }
878
879 pub async fn receive_joined_timeline_event(
880 &mut self,
881 room_id: &RoomId,
882 event: AnySyncRoomEvent,
883 ) {
884 let room = self.get_or_create_room(room_id);
885 room.handle_sync_room_event(event).await
886 }
887
888 pub fn receive_login(&mut self, response: LoginResponse) {
889 let login_state = LoginInfo {
890 user_id: response.user_id,
891 };
892 self.login_state = Some(login_state);
893 }
894
895 fn create_server_dir(&self) -> std::io::Result<()> {
896 let path = self.get_server_path();
897 std::fs::create_dir_all(path)
898 }
899
900 pub fn get_server_path(&self) -> PathBuf {
901 let mut path = Weechat::home_dir();
902 let server_name: &str = &self.server_name;
903 path.push("matrix-rust");
904 path.push(server_name);
905
906 path
907 }
908
909 pub fn create_client(&mut self) -> Result<Client, ServerError> {
910 let settings = self.settings.clone();
911
912 let homeserver = settings.homeserver.as_ref().ok_or_else(|| {
913 ServerError::StartError("Homeserver not configured".to_owned())
914 })?;
915
916 self.create_server_dir().map_err(|e| {
917 ServerError::IoError(format!(
918 "Error creating the session dir: {}",
919 e
920 ))
921 })?;
922
923 let mut client_config =
924 ClientConfig::new().store_path(self.get_server_path());
925
926 if let Some(proxy) = settings.proxy.as_ref() {
927 client_config = client_config.proxy(proxy.as_str()).unwrap();
928 }
929
930 if !settings.ssl_verify {
931 client_config = client_config.disable_ssl_verification();
932 }
933
934 let client =
935 Client::new_with_config(homeserver.clone(), client_config).unwrap();
936 self.current_settings = settings;
937 self.client = Some(client.clone());
938
939 Ok(client)
940 }
941}