src/server.rs

13150d5bf8ad99b3666010f5e5cba56bd145dc52
weechat-matrix-rs/src/server.rs history · blame · raw

770 lines · 24201 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 futures::executor::block_on;
 59use indoc::indoc;
 60use std::{
 61    cell::{Ref, RefCell, RefMut},
 62    collections::HashMap,
 63    path::PathBuf,
 64    rc::{Rc, Weak},
 65    sync::Arc,
 66};
 67use url::Url;
 68
 69use matrix_sdk::{
 70    self,
 71    api::r0::session::login::Response as LoginResponse,
 72    events::{AnySyncRoomEvent, AnySyncStateEvent},
 73    identifiers::{RoomId, UserId},
 74    locks::RwLock,
 75    Client, ClientConfig, Room,
 76};
 77
 78use weechat::{
 79    buffer::{BufferBuilder, BufferHandle},
 80    config::{BooleanOptionSettings, ConfigSection, StringOptionSettings},
 81    Weechat,
 82};
 83
 84use crate::{
 85    config::Config, connection::Connection, room::RoomBuffer, ConfigHandle,
 86};
 87
 88#[derive(Debug)]
 89pub enum ServerError {
 90    StartError(String),
 91    IoError(String),
 92}
 93
 94#[derive(Default)]
 95pub struct ServerSettings {
 96    pub homeserver: Option<Url>,
 97    pub proxy: Option<Url>,
 98    pub autoconnect: bool,
 99    pub username: String,
100    pub password: String,
101}
102
103impl ServerSettings {
104    pub fn new() -> Self {
105        Default::default()
106    }
107}
108
109pub struct LoginInfo {
110    user_id: UserId,
111}
112
113#[derive(Clone)]
114pub struct MatrixServer {
115    #[allow(clippy::rc_buffer)]
116    server_name: Rc<String>,
117    inner: Rc<RefCell<InnerServer>>,
118}
119
120impl std::fmt::Debug for MatrixServer {
121    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        let mut fmt = f.debug_struct("MatrixServer");
123        fmt.field("name", &self.server_name).finish()
124    }
125}
126
127pub struct InnerServer {
128    #[allow(clippy::rc_buffer)]
129    server_name: Rc<String>,
130    pub room_buffers: HashMap<RoomId, RoomBuffer>,
131    settings: ServerSettings,
132    config: ConfigHandle,
133    client: Option<Client>,
134    login_state: Option<LoginInfo>,
135    connection: Rc<RefCell<Option<Connection>>>,
136    server_buffer: Rc<RefCell<Option<BufferHandle>>>,
137}
138
139impl MatrixServer {
140    pub fn new(
141        name: &str,
142        config: &ConfigHandle,
143        server_section: &mut ConfigSection,
144    ) -> Self {
145        let server_name = Rc::new(name.to_owned());
146
147        let server = InnerServer {
148            server_name: server_name.clone(),
149            room_buffers: HashMap::new(),
150            settings: ServerSettings::new(),
151            config: config.clone(),
152            client: None,
153            login_state: None,
154            connection: Rc::new(RefCell::new(None)),
155            server_buffer: Rc::new(RefCell::new(None)),
156        };
157
158        let server = Rc::new(RefCell::new(server));
159        MatrixServer::create_server_conf(&server_name, server_section, &server);
160
161        MatrixServer {
162            server_name,
163            inner: server,
164        }
165    }
166
167    pub fn name(&self) -> &str {
168        &self.server_name
169    }
170
171    pub fn inner(&self) -> Ref<'_, InnerServer> {
172        self.inner.borrow()
173    }
174
175    pub fn clone_inner_weak(&self) -> Weak<RefCell<InnerServer>> {
176        Rc::downgrade(&self.inner)
177    }
178
179    pub fn connection(&self) -> Rc<RefCell<Option<Connection>>> {
180        self.inner().connection.clone()
181    }
182
183    pub async fn devices(&self) {
184        let connection = self.connection();
185
186        if let Some(c) = &*connection.borrow() {
187            let response = match c.devices().await {
188                Ok(r) => r,
189                Err(e) => {
190                    self.print_error(&format!(
191                        "Error fetching devices {:?}",
192                        e
193                    ));
194                    return;
195                }
196            };
197
198            if response.devices.is_empty() {
199                self.print_error("No devices were found for this server");
200                return;
201            }
202
203            self.print_network(&format!(
204                indoc!(
205                    "
206                    Devices for server {}{}{}:
207                      Device ID      Device name                   Last seen
208                "
209                ),
210                Weechat::color("chat_server"),
211                self.name(),
212                Weechat::color("reset")
213            ));
214
215            let lines: Vec<String> = response
216                .devices
217                .iter()
218                .map(|d| {
219                    let device_color = Weechat::info_get(
220                        "nick_color_name",
221                        d.device_id.as_str(),
222                    )
223                    .expect("Can't get device color");
224
225                    let last_seen_date =
226                        d.last_seen_ts.map_or("?".to_owned(), |d| {
227                            let date: DateTime<Utc> = d.into();
228                            date.format("%Y/%m/%d %H:%M").to_string()
229                        });
230
231                    let last_seen = format!(
232                        "{} @ {}",
233                        d.last_seen_ip.as_deref().unwrap_or("-"),
234                        last_seen_date
235                    );
236
237                    format!(
238                        "  {}{:<15}{}{:<30}{:<}",
239                        Weechat::color(&device_color),
240                        d.device_id.as_str(),
241                        Weechat::color("reset"),
242                        d.display_name.as_deref().unwrap_or(""),
243                        last_seen,
244                    )
245                })
246                .collect();
247
248            let line = lines.join("\n");
249            self.print_network(&line);
250        };
251    }
252
253    /// Parse an URL returning a None if the string is empty.
254    ///
255    /// # Panics
256    ///
257    /// This panics if the string can't be parsed as an URL.
258    fn parse_url_unchecked(value: &str) -> Option<Url> {
259        if value.is_empty() {
260            None
261        } else {
262            Some(
263                Url::parse(value)
264                    .expect("Can't parse URL, did the check callback fail?"),
265            )
266        }
267    }
268
269    /// Parse an URL returning an error if the parse step fails.
270    pub fn parse_url(value: String) -> Result<(), String> {
271        let url = Url::parse(&value);
272
273        match url {
274            Ok(u) => {
275                if u.cannot_be_a_base() {
276                    Err(String::from("The Homeserver URL is missing a schema"))
277                } else {
278                    Ok(())
279                }
280            }
281            Err(e) => Err(e.to_string()),
282        }
283    }
284
285    /// Check if the provided value is a valid URL.
286    fn is_url_valid(value: &str) -> bool {
287        if value.is_empty() {
288            true
289        } else {
290            MatrixServer::parse_url(value.to_string()).is_ok()
291        }
292    }
293
294    fn create_server_conf(
295        server_name: &str,
296        server_section: &mut ConfigSection,
297        server_ref: &Rc<RefCell<InnerServer>>,
298    ) {
299        let server = Rc::downgrade(server_ref);
300        let server_copy = server.clone();
301        let autoconnect =
302            BooleanOptionSettings::new(format!("{}.autoconnect", server_name))
303                .set_change_callback(move |_, option| {
304                    let server = server.clone();
305                    let value = option.value();
306
307                    let server_ref = server.upgrade().expect(
308                        "Server got deleted while server config is alive",
309                    );
310
311                    let mut server = server_ref.borrow_mut();
312                    server.settings.autoconnect = value;
313                });
314
315        server_section
316            .new_boolean_option(autoconnect)
317            .expect("Can't create autoconnect option");
318
319        let server = server_copy;
320        let server_copy = server.clone();
321
322        let homeserver =
323            StringOptionSettings::new(format!("{}.homeserver", server_name))
324                .set_check_callback(|_, _, value| {
325                    MatrixServer::is_url_valid(&value)
326                })
327                .set_change_callback(move |_, option| {
328                    let server = server.clone();
329                    let server_ref = server.upgrade().expect(
330                        "Server got deleted while server config is alive",
331                    );
332
333                    let mut server = server_ref.borrow_mut();
334
335                    server.settings.homeserver =
336                        MatrixServer::parse_url_unchecked(&option.value());
337                });
338
339        server_section
340            .new_string_option(homeserver)
341            .expect("Can't create homeserver option");
342
343        let server = server_copy;
344        let server_copy = server.clone();
345
346        let proxy = StringOptionSettings::new(format!("{}.proxy", server_name))
347            .set_check_callback(|_, _, value| {
348                MatrixServer::is_url_valid(&value)
349            })
350            .set_change_callback(move |_, option| {
351                let server = server.clone();
352                let server_ref = server
353                    .upgrade()
354                    .expect("Server got deleted while server config is alive");
355
356                let mut server = server_ref.borrow_mut();
357                server.settings.proxy =
358                    MatrixServer::parse_url_unchecked(&option.value());
359            });
360
361        server_section
362            .new_string_option(proxy)
363            .expect("Can't create proxy option");
364
365        let server = server_copy;
366        let server_copy = server.clone();
367
368        let username =
369            StringOptionSettings::new(format!("{}.username", server_name))
370                .set_change_callback(move |_, option| {
371                    let server = server.clone();
372
373                    let server_ref = server.upgrade().expect(
374                        "Server got deleted while server config is alive",
375                    );
376
377                    let mut server = server_ref.borrow_mut();
378                    server.settings.username = option.value().to_string();
379                });
380
381        server_section
382            .new_string_option(username)
383            .expect("Can't create username option");
384
385        let server = server_copy;
386
387        let password =
388            StringOptionSettings::new(format!("{}.password", server_name))
389                .set_change_callback(move |_, option| {
390                    let server = server.clone();
391
392                    let server_ref = server.upgrade().expect(
393                        "Server got deleted while server config is alive",
394                    );
395
396                    let mut server = server_ref.borrow_mut();
397                    server.settings.password = option.value().to_string();
398                });
399
400        server_section
401            .new_string_option(password)
402            .expect("Can't create password option");
403    }
404
405    pub fn connected(&self) -> bool {
406        self.inner.borrow().connected()
407    }
408
409    pub fn autoconnect(&self) -> bool {
410        self.inner.borrow().settings.autoconnect
411    }
412
413    pub fn connect(&self) -> Result<(), ServerError> {
414        if self.connected() {
415            self.print_error(&format!(
416                "Already connected to {}{}{}",
417                Weechat::color("chat_server"),
418                self.name(),
419                Weechat::color("reset")
420            ));
421
422            return Ok(());
423        }
424
425        let client = self.inner.borrow_mut().get_or_creaet_client()?;
426        let connection = Connection::new(&self, &client);
427
428        *self.inner.borrow_mut().connection.borrow_mut() = Some(connection);
429
430        self.print_network(&format!(
431            "Connected to {}{}{}",
432            Weechat::color("chat_server"),
433            self.name(),
434            Weechat::color("reset")
435        ));
436
437        Ok(())
438    }
439
440    pub fn print(&self, message: &str) {
441        self.inner().print(message)
442    }
443
444    pub fn print_with_prefix(&self, prefix: &str, message: &str) {
445        self.inner().print_with_prefix(prefix, message)
446    }
447
448    pub fn print_network(&self, message: &str) {
449        self.inner().print_network(message)
450    }
451
452    pub fn print_error(&self, message: &str) {
453        self.inner().print_error(message)
454    }
455
456    pub fn disconnect(&self) {
457        if !self.connected() {
458            self.print_error(&format!(
459                "Not connected to {}{}{}",
460                Weechat::color("chat_server"),
461                self.name(),
462                Weechat::color("reset")
463            ));
464
465            return;
466        }
467
468        {
469            let server = self.inner();
470            let mut connection = server.connection.borrow_mut();
471            connection.take();
472        }
473
474        self.print_network(&format!(
475            "Disconnected from {}{}{}",
476            Weechat::color("chat_server"),
477            self.name(),
478            Weechat::color("reset")
479        ));
480    }
481
482    pub fn get_info_str(&self, details: bool) -> String {
483        let mut s = String::from(&format!(
484            "{}{}{} [{}]",
485            Weechat::color("chat_server"),
486            self.server_name.as_ref().to_owned(),
487            Weechat::color("reset"),
488            if self.connected() {
489                "connected"
490            } else {
491                "not connected"
492            }
493        ));
494
495        if !details {
496            return s;
497        }
498
499        let settings = &self.inner.borrow().settings;
500        s.push_str(&format!(
501            "\n\
502                 {:indent$}homeserver: {}\n\
503                 {:indent$}proxy: {}\n\
504                 {:indent$}autoconnect: {}\n\
505                 {:indent$}username: {}\n",
506            "",
507            settings.homeserver.as_ref().map_or("", |url| url.as_str()),
508            "",
509            settings.proxy.as_ref().map_or("", |url| url.as_str()),
510            "",
511            settings.autoconnect,
512            "",
513            settings.username,
514            indent = 8
515        ));
516        s
517    }
518}
519
520impl Drop for MatrixServer {
521    fn drop(&mut self) {
522        // TODO close all the server buffers.
523        let config = &self.inner.borrow().config;
524        let mut config_borrow = config.borrow_mut();
525
526        let mut section = config_borrow
527            .search_section_mut("server")
528            .expect("Can't get server section");
529
530        for option_name in
531            &["homeserver", "autoconnect", "password", "proxy", "username"]
532        {
533            let option_name = &format!("{}.{}", self.name(), option_name);
534            section.free_option(option_name).unwrap_or_else(|_| {
535                panic!(format!("Can't free option {}", option_name))
536            });
537        }
538    }
539}
540
541impl InnerServer {
542    pub(crate) fn get_or_create_room(
543        &mut self,
544        room_id: &RoomId,
545    ) -> &mut RoomBuffer {
546        if !self.room_buffers.contains_key(room_id) {
547            let homeserver = self
548                .settings
549                .homeserver
550                .as_ref()
551                .expect("Creating room buffer while no homeserver");
552            let login_state = self
553                .login_state
554                .as_ref()
555                .expect("Receiving events while not being logged in");
556            let room = block_on(
557                self.client
558                    .as_ref()
559                    .expect("Receiving events without a client")
560                    .get_joined_room(room_id),
561            );
562            let room =
563                room.expect("Receiving events for a room while no room found");
564            let buffer = RoomBuffer::new(
565                &self.connection,
566                self.config.inner.clone(),
567                room,
568                homeserver,
569                room_id.clone(),
570                &login_state.user_id,
571            );
572            self.room_buffers.insert(room_id.clone(), buffer);
573        }
574
575        self.room_buffers.get_mut(room_id).unwrap()
576    }
577
578    pub fn settings(&self) -> &ServerSettings {
579        &self.settings
580    }
581
582    pub fn room_buffers(&self) -> &HashMap<RoomId, RoomBuffer> {
583        &self.room_buffers
584    }
585
586    pub fn config(&self) -> Ref<Config> {
587        self.config.borrow()
588    }
589
590    pub fn restore_room(&mut self, room: Arc<RwLock<Room>>) {
591        let homeserver = self
592            .settings
593            .homeserver
594            .as_ref()
595            .expect("Creating room buffer while no homeserver");
596
597        let buffer = RoomBuffer::restore(
598            room,
599            &self.connection,
600            self.config.inner.clone(),
601            homeserver,
602        );
603        let room_id = buffer.room_id().to_owned();
604
605        self.room_buffers.insert(room_id, buffer);
606    }
607
608    fn create_server_buffer(&self) -> BufferHandle {
609        let buffer_handle =
610            BufferBuilder::new(&format!("server.{}", self.server_name))
611                .build()
612                .expect("Can't create Matrix debug buffer");
613
614        let buffer = buffer_handle
615            .upgrade()
616            .expect("Can't upgrade newly created server buffer");
617
618        buffer.set_short_name(&self.server_name);
619        buffer.set_localvar("type", "server");
620        buffer.set_localvar("nick", &self.settings.username);
621        buffer.set_localvar("server", &self.server_name);
622
623        buffer_handle
624    }
625
626    fn get_or_creaet_client(&mut self) -> Result<Client, ServerError> {
627        let client = if let Some(c) = self.client.as_ref() {
628            c.clone()
629        } else {
630            self.create_client()?
631        };
632
633        // Check if the homeserver setting changed and swap our client if it
634        // did.
635        if client.homeserver()
636            != self
637                .settings
638                .homeserver
639                .as_ref()
640                .expect("Homeserver URL isn't set")
641        {
642            // TODO close all the room buffers of the server here, they don't
643            // belong to our client anymore.
644            self.create_client()
645        } else {
646            Ok(client)
647        }
648    }
649
650    /// Borrow the server buffer handle.
651    pub fn server_buffer(&self) -> Ref<Option<BufferHandle>> {
652        self.server_buffer.borrow()
653    }
654
655    fn get_or_create_buffer<'a>(
656        &self,
657        server_buffer: &'a mut RefMut<Option<BufferHandle>>,
658    ) -> &'a BufferHandle {
659        if let Some(buffer) = server_buffer.as_ref() {
660            if buffer.upgrade().is_err() {
661                let buffer = self.create_server_buffer();
662                **server_buffer = Some(buffer);
663            }
664        } else {
665            let buffer = self.create_server_buffer();
666            **server_buffer = Some(buffer);
667        }
668
669        server_buffer.as_ref().unwrap()
670    }
671
672    /// Print a neutral message to the server buffer.
673    pub fn print(&self, message: &str) {
674        let mut server_buffer = self.server_buffer.borrow_mut();
675        let buffer = self
676            .get_or_create_buffer(&mut server_buffer)
677            .upgrade()
678            .unwrap();
679        buffer.print(message);
680    }
681
682    /// Print a message with a given prefix to the server buffer.
683    pub fn print_with_prefix(&self, prefix: &str, message: &str) {
684        self.print(&format!("{}{}", prefix, message));
685    }
686
687    /// Print an network message to the server buffer.
688    pub fn print_network(&self, message: &str) {
689        self.print_with_prefix(Weechat::prefix("network"), message);
690    }
691
692    /// Print an error message to the server buffer.
693    pub fn print_error(&self, message: &str) {
694        self.print_with_prefix(Weechat::prefix("error"), message);
695    }
696
697    /// Is the server connected.
698    pub fn connected(&self) -> bool {
699        self.connection.borrow().is_some()
700    }
701
702    pub fn receive_joined_state_event(
703        &mut self,
704        room_id: &RoomId,
705        event: AnySyncStateEvent,
706    ) {
707        let room = self.get_or_create_room(room_id);
708        room.handle_sync_state_event(event)
709    }
710
711    pub fn receive_joined_timeline_event(
712        &mut self,
713        room_id: &RoomId,
714        event: AnySyncRoomEvent,
715    ) {
716        let room = self.get_or_create_room(room_id);
717        room.handle_sync_room_event(event)
718    }
719
720    pub fn receive_login(&mut self, response: LoginResponse) {
721        let login_state = LoginInfo {
722            user_id: response.user_id,
723        };
724        self.login_state = Some(login_state);
725    }
726
727    fn create_server_dir(&self) -> std::io::Result<()> {
728        let path = self.get_server_path();
729        std::fs::create_dir_all(path)
730    }
731
732    pub fn get_server_path(&self) -> PathBuf {
733        let mut path = Weechat::home_dir();
734        let server_name: &str = &self.server_name;
735        path.push("matrix-rust");
736        path.push(server_name);
737
738        path
739    }
740
741    pub fn create_client(&mut self) -> Result<Client, ServerError> {
742        let homeserver =
743            self.settings.homeserver.as_ref().ok_or_else(|| {
744                ServerError::StartError("Homeserver not configured".to_owned())
745            })?;
746
747        self.create_server_dir().map_err(|e| {
748            ServerError::IoError(format!(
749                "Error creating the session dir: {}",
750                e
751            ))
752        })?;
753
754        let mut client_config =
755            ClientConfig::new().store_path(self.get_server_path());
756
757        if let Some(proxy) = &self.settings.proxy {
758            client_config = client_config
759                .proxy(proxy.as_str())
760                .unwrap()
761                .disable_ssl_verification();
762        }
763
764        let client =
765            Client::new_with_config(homeserver.clone(), client_config).unwrap();
766        self.client = Some(client.clone());
767
768        Ok(client)
769    }
770}