src/server.rs

7ef7a0d8424ae79fada0a8a4711cab8b48b50a4d
weechat-matrix-rs/src/server.rs history · blame · raw

807 lines · 26244 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 two tasks, one for
 10//! the sync loop and one to send out room messages.
 11//!
 12//! If will also spawn a task on the Weechat mainloop, this one waits for
 13//! responses from the sync loop.
 14//!
 15//!
 16//! Schematically this looks like the following diagram.
 17//!
 18//!                                 MatrixServer
 19//!   +--------------------------------------------------------------------+
 20//!   |                                                                    |
 21//!   |         Weechat mainloop                     Tokio runtime         |
 22//!   |   +---------------------------+        +------------------------+  |
 23//!   |   |                           |        |                        |  |
 24//!   |   |  +--------------------+   |        |   +----------------+   |  |
 25//!   |   |  |                    |   |        |   |                |   |  |
 26//!   |   |  |  Response receiver +<---------------+   Sync loop    |   |  |
 27//!   |   |  |                    |   |        |   |                |   |  |
 28//!   |   |  |                    |   |        |   |                |   |  |
 29//!   |   |  +--------------------+   |        |   +----------------+   |  |
 30//!   |   |                           |        |                        |  |
 31//!   |   |  +--------------------+   |        |   +----------------+   |  |
 32//!   |   |  |                    |   |        |   |                |   |  |
 33//!   |   |  |  Roombuffer input  +--------------->+   Send loop    |   |  |
 34//!   |   |  |      callback      +<---------------+                |   |  |
 35//!   |   |  |                    |   |        |   |                |   |  |
 36//!   |   |  +--------------------+   |        |   +----------------+   |  |
 37//!   |   |                           |        |                        |  |
 38//!   |   +---------------------------+        +------------------------+  |
 39//!   |                                                                    |
 40//!   +--------------------------------------------------------------------+
 41//!
 42//!
 43//! The tokio runtime and response receiver task will be alive only if the user
 44//! connects to the server while the room buffer input callback will print an
 45//! error if the server is disconnected.
 46//!
 47//! The server holds all the rooms which in turn hold the buffers, users, and
 48//! room metadata.
 49//!
 50//! The response receiver forwards events to the correct room. The response
 51//! receiver fetches events individually from a mpsc channel. This makes sure
 52//! that processing events will not block the Weechat mainloop for too long.
 53
 54use async_std::sync::channel as async_channel;
 55use async_std::sync::{Receiver, Sender};
 56use std::cell::{Ref, RefCell};
 57use std::collections::HashMap;
 58use std::path::PathBuf;
 59use std::rc::{Rc, Weak};
 60use std::time::Duration;
 61use tokio::runtime::Runtime;
 62use url::Url;
 63use uuid::Uuid;
 64
 65use matrix_sdk::api::r0::session::login::Response as LoginResponse;
 66
 67use matrix_sdk::{
 68    self,
 69    events::{
 70        collections::all::{RoomEvent, StateEvent},
 71        room::message::{MessageEventContent, TextMessageEventContent},
 72    },
 73    identifiers::{RoomId, UserId},
 74    Client, ClientConfig, Room, SyncSettings,
 75};
 76
 77use weechat::config::{
 78    BooleanOptionSettings, ConfigSection, StringOptionSettings,
 79};
 80use weechat::JoinHandle;
 81use weechat::Weechat;
 82
 83use crate::room_buffer::RoomBuffer;
 84use crate::PLUGIN_NAME;
 85use crate::{config::Config, ConfigHandle};
 86
 87const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
 88
 89pub enum ThreadMessage {
 90    LoginMessage(LoginResponse),
 91    SyncState(RoomId, StateEvent),
 92    SyncEvent(RoomId, RoomEvent),
 93    RestoredRoom(Room),
 94}
 95
 96#[derive(Debug)]
 97pub enum ServerError {
 98    StartError(String),
 99    IoError(String),
100}
101
102pub enum ServerMessage {
103    RoomSend(RoomId, String),
104}
105
106#[derive(Default)]
107pub struct ServerSettings {
108    homeserver: Option<Url>,
109    proxy: Option<Url>,
110    autoconnect: bool,
111    username: String,
112    password: String,
113}
114
115impl ServerSettings {
116    pub fn new() -> Self {
117        Default::default()
118    }
119}
120
121pub struct LoginState {
122    user_id: UserId,
123}
124
125pub struct Connection {
126    client_channel: Sender<ServerMessage>,
127    response_receiver: JoinHandle<(), ()>,
128    // TODO move the runtime into the plugin, once we're able to cancel tokio
129    // tasks.
130    #[used]
131    runtime: Runtime,
132}
133
134impl Connection {
135    pub async fn send_message(&self, room_id: &RoomId, message: &str) {
136        self.client_channel
137            .send(ServerMessage::RoomSend(
138                room_id.to_owned(),
139                message.to_owned(),
140            ))
141            .await;
142    }
143}
144
145#[derive(Clone)]
146pub(crate) struct MatrixServer {
147    server_name: Rc<String>,
148    inner: Rc<RefCell<InnerServer>>,
149}
150
151impl std::fmt::Debug for MatrixServer {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        let mut fmt = f.debug_struct("MatrixServer");
154        fmt.field("name", &self.server_name).finish()
155    }
156}
157
158pub(crate) struct InnerServer {
159    server_name: Rc<String>,
160    room_buffers: HashMap<RoomId, RoomBuffer>,
161    settings: ServerSettings,
162    config: ConfigHandle,
163    client: Option<Client>,
164    login_state: Option<LoginState>,
165    connected_state: Rc<RefCell<Option<Connection>>>,
166}
167
168impl MatrixServer {
169    pub fn new(
170        name: &str,
171        config: &ConfigHandle,
172        server_section: &mut ConfigSection,
173    ) -> Self {
174        let server_name = Rc::new(name.to_owned());
175
176        let server = InnerServer {
177            server_name: server_name.clone(),
178            room_buffers: HashMap::new(),
179            settings: ServerSettings::new(),
180            config: config.clone(),
181            client: None,
182            login_state: None,
183            connected_state: Rc::new(RefCell::new(None)),
184        };
185
186        let server = Rc::new(RefCell::new(server));
187        MatrixServer::create_server_conf(&server_name, server_section, &server);
188
189        MatrixServer {
190            server_name,
191            inner: server,
192        }
193    }
194
195    pub fn name(&self) -> &str {
196        &self.server_name
197    }
198
199    pub fn inner(&self) -> Ref<'_, InnerServer> {
200        self.inner.borrow()
201    }
202
203    pub fn parse_homeserver_url(value: String) -> Result<(), String> {
204        let url = Url::parse(&value);
205
206        match url {
207            Ok(u) => {
208                if u.cannot_be_a_base() {
209                    Err(String::from("The Homeserver URL is missing a schema"))
210                } else {
211                    Ok(())
212                }
213            }
214            Err(e) => Err(e.to_string()),
215        }
216    }
217
218    fn create_server_conf(
219        server_name: &str,
220        server_section: &mut ConfigSection,
221        server_ref: &Rc<RefCell<InnerServer>>,
222    ) {
223        let server = Rc::downgrade(server_ref);
224        let server_copy = server.clone();
225        let autoconnect =
226            BooleanOptionSettings::new(format!("{}.autoconnect", server_name))
227                .set_change_callback(move |_, option| {
228                    let server = server.clone();
229                    let value = option.value();
230
231                    let server_ref = server.upgrade().expect(
232                        "Server got deleted while server config is alive",
233                    );
234
235                    let mut server = server_ref.borrow_mut();
236                    server.settings.autoconnect = value;
237                });
238
239        server_section
240            .new_boolean_option(autoconnect)
241            .expect("Can't create autoconnect option");
242
243        let server = server_copy;
244        let server_copy = server.clone();
245
246        let homeserver =
247            StringOptionSettings::new(format!("{}.homeserver", server_name))
248                .set_check_callback(|_, _, value| {
249                    if value.is_empty() {
250                        true
251                    } else {
252                        MatrixServer::parse_homeserver_url(value.to_string())
253                            .is_ok()
254                    }
255                })
256                .set_change_callback(move |_, option| {
257                    let server = server.clone();
258                    let server_ref = server.upgrade().expect(
259                        "Server got deleted while server config is alive",
260                    );
261
262                    let mut server = server_ref.borrow_mut();
263                    let homeserver = Url::parse(option.value().as_ref()).expect(
264                "Can't parse homeserver URL, did the check callback fail?",
265                    );
266
267                    server.settings.homeserver = Some(homeserver)
268                });
269
270        server_section
271            .new_string_option(homeserver)
272            .expect("Can't create homeserver option");
273
274        let server = server_copy;
275        let server_copy = server.clone();
276
277        let proxy = StringOptionSettings::new(format!("{}.proxy", server_name))
278            .set_check_callback(|_, _, value| {
279                if value.is_empty() {
280                    true
281                } else {
282                    MatrixServer::parse_homeserver_url(value.to_string())
283                        .is_ok()
284                }
285            })
286            .set_change_callback(move |_, option| {
287                let server = server.clone();
288                let server_ref = server
289                    .upgrade()
290                    .expect("Server got deleted while server config is alive");
291
292                let mut server = server_ref.borrow_mut();
293                let proxy = Url::parse(option.value().as_ref()).expect(
294                    "Can't parse proxy URL, did the check callback fail?",
295                );
296
297                server.settings.proxy = Some(proxy)
298            });
299
300        server_section
301            .new_string_option(proxy)
302            .expect("Can't create proxy option");
303
304        let server = server_copy;
305        let server_copy = server.clone();
306
307        let username =
308            StringOptionSettings::new(format!("{}.username", server_name))
309                .set_change_callback(move |_, option| {
310                    let server = server.clone();
311
312                    let server_ref = server.upgrade().expect(
313                        "Server got deleted while server config is alive",
314                    );
315
316                    let mut server = server_ref.borrow_mut();
317                    server.settings.username = option.value().to_string();
318                });
319
320        server_section
321            .new_string_option(username)
322            .expect("Can't create username option");
323
324        let server = server_copy;
325
326        let password =
327            StringOptionSettings::new(format!("{}.password", server_name))
328                .set_change_callback(move |_, option| {
329                    let server = server.clone();
330
331                    let server_ref = server.upgrade().expect(
332                        "Server got deleted while server config is alive",
333                    );
334
335                    let mut server = server_ref.borrow_mut();
336                    server.settings.password = option.value().to_string();
337                });
338
339        server_section
340            .new_string_option(password)
341            .expect("Can't create password option");
342    }
343
344    pub fn connected(&self) -> bool {
345        self.inner.borrow().connected()
346    }
347
348    pub fn autoconnect(&self) -> bool {
349        self.inner.borrow().settings.autoconnect
350    }
351
352    fn save_device_id(
353        user_name: &str,
354        mut server_path: PathBuf,
355        response: &LoginResponse,
356    ) -> std::io::Result<()> {
357        server_path.push(user_name);
358        server_path.set_extension("device_id");
359        std::fs::write(&server_path, &response.device_id)
360    }
361
362    fn load_device_id(
363        user_name: &str,
364        mut server_path: PathBuf,
365    ) -> std::io::Result<Option<String>> {
366        server_path.push(user_name);
367        server_path.set_extension("device_id");
368
369        let device_id = std::fs::read_to_string(server_path);
370
371        if let Err(e) = device_id {
372            // A file not found error is ok, report the rest.
373            if e.kind() != std::io::ErrorKind::NotFound {
374                return Err(e);
375            }
376            return Ok(None);
377        };
378
379        let device_id = device_id.unwrap_or_default();
380
381        if device_id.is_empty() {
382            Ok(None)
383        } else {
384            Ok(Some(device_id))
385        }
386    }
387
388    pub fn connect(&self) -> Result<(), ServerError> {
389        if self.connected() {
390            return Ok(());
391        }
392
393        let runtime = Runtime::new().unwrap();
394        let mut server = self.inner.borrow_mut();
395
396        let client = if let Some(c) = server.client.as_ref() {
397            c.clone()
398        } else {
399            server.create_client()?
400        };
401
402        // Check if the homeserver setting changed and swap our client if it
403        // did.
404        let client = if client.homeserver()
405            != server.settings.homeserver.as_ref().unwrap()
406        {
407            // TODO close all the room buffers of the server here, they don't
408            // belong to our client anymore.
409            server.create_client()?
410        } else {
411            client
412        };
413
414        let (tx, rx) = async_channel(1000);
415        runtime.spawn(MatrixServer::sync_loop(
416            client.clone(),
417            tx,
418            server.settings.username.to_string(),
419            server.settings.password.to_string(),
420            server.server_name.to_string(),
421            server.get_server_path(),
422        ));
423        let response_receiver = Weechat::spawn(
424            MatrixServer::response_receiver(rx, Rc::downgrade(&self.inner)),
425        );
426
427        let (client_sender, client_receiver) = async_channel(10);
428        runtime.spawn(MatrixServer::send_loop(client, client_receiver));
429
430        let mut connected_state = server.connected_state.borrow_mut();
431
432        *connected_state = Some(Connection {
433            response_receiver,
434            client_channel: client_sender,
435            runtime,
436        });
437
438        Ok(())
439    }
440
441    pub fn disconnect(&self) {
442        // TODO these messages should go to the server buffer.
443        if !self.connected() {
444            Weechat::print(&format!(
445                "{}{}: Server {}{}{} is not connected.",
446                Weechat::prefix("error"),
447                PLUGIN_NAME,
448                Weechat::color("chat_server"),
449                self.name(),
450                Weechat::color("reset")
451            ));
452
453            return;
454        }
455
456        let server = self.inner.borrow_mut();
457        let mut connected_state = server.connected_state.borrow_mut();
458        let state = connected_state.take();
459
460        if let Some(s) = state {
461            s.response_receiver.cancel();
462        }
463
464        Weechat::print(&format!("{}: Disconnected from server.", PLUGIN_NAME));
465    }
466
467    /// Main client sync loop.
468    /// This runs on the per server tokio executor.
469    /// It communicates with the main Weechat thread using a async channel.
470    pub async fn sync_loop(
471        client: Client,
472        channel: Sender<Result<ThreadMessage, String>>,
473        username: String,
474        password: String,
475        server_name: String,
476        server_path: PathBuf,
477    ) {
478        if !client.logged_in().await {
479            let device_id =
480                MatrixServer::load_device_id(&username, server_path.clone());
481
482            let device_id = match device_id {
483                Err(e) => {
484                    channel
485                        .send(Err(format!(
486                        "Error while reading the device id for server {}: {:?}",
487                        server_name, e
488                    )))
489                        .await;
490                    return;
491                }
492                Ok(d) => d,
493            };
494
495            let first_login = device_id.is_none();
496
497            let ret = client
498                .login(
499                    username.clone(),
500                    password,
501                    device_id,
502                    Some("Weechat-Matrix-rs".to_owned()),
503                )
504                .await;
505
506            match ret {
507                Ok(response) => {
508                    if let Err(e) = MatrixServer::save_device_id(
509                        &username,
510                        server_path.clone(),
511                        &response,
512                    ) {
513                        channel
514                            .send(Err(format!(
515                            "Error while writing the device id for server {}: {:?}",
516                            server_name, e
517                        ))).await;
518                        return;
519                    }
520
521                    channel
522                        .send(Ok(ThreadMessage::LoginMessage(response)))
523                        .await
524                }
525                Err(e) => {
526                    channel
527                        .send(Err(format!("Failed to log in: {:?}", e)))
528                        .await;
529                    return;
530                }
531            }
532
533            if !first_login {
534                let joined_rooms = client.joined_rooms();
535                for room in joined_rooms.read().await.values() {
536                    let room = room.read().await;
537                    let room: &Room = &*room;
538                    channel
539                        .send(Ok(ThreadMessage::RestoredRoom(room.clone())))
540                        .await
541                }
542            }
543        }
544
545        let sync_token = client.sync_token().await;
546        let sync_settings = SyncSettings::new().timeout(DEFAULT_SYNC_TIMEOUT);
547
548        let sync_settings = if let Some(t) = sync_token {
549            sync_settings.token(t)
550        } else {
551            sync_settings
552        };
553
554        let sync_channel = &channel;
555
556        client
557            .sync_forever(sync_settings, async move |response| {
558                let channel = sync_channel;
559
560                for (room_id, room) in response.rooms.join {
561                    for event in room.state.events {
562                        if let Ok(e) = event.deserialize() {
563                            channel
564                                .send(Ok(ThreadMessage::SyncState(
565                                    room_id.clone(),
566                                    e,
567                                )))
568                                .await;
569                        }
570                    }
571                    for event in room.timeline.events {
572                        if let Ok(e) = event.deserialize() {
573                            channel
574                                .send(Ok(ThreadMessage::SyncEvent(
575                                    room_id.clone(),
576                                    e,
577                                )))
578                                .await;
579                        }
580                    }
581                }
582            })
583            .await;
584    }
585
586    /// Response receiver loop.
587    /// This runs on the main Weechat thread and listens for responses coming
588    /// from the client running in the tokio executor.
589    pub async fn response_receiver(
590        receiver: Receiver<Result<ThreadMessage, String>>,
591        server: Weak<RefCell<InnerServer>>,
592    ) {
593        loop {
594            let ret = match receiver.recv().await {
595                Ok(m) => m,
596                Err(e) => {
597                    Weechat::print(&format!(
598                        "Error receiving message: {:?}",
599                        e
600                    ));
601                    return;
602                }
603            };
604
605            let server_cell = server
606                .upgrade()
607                .expect("Can't upgrade server in sync receiver");
608            let mut server = server_cell.borrow_mut();
609
610            match ret {
611                Ok(message) => match message {
612                    ThreadMessage::LoginMessage(r) => server.receive_login(r),
613                    ThreadMessage::SyncEvent(r, e) => {
614                        server.receive_joined_timeline_event(&r, e)
615                    }
616                    ThreadMessage::SyncState(r, e) => {
617                        server.receive_joined_state_event(&r, e)
618                    }
619                    ThreadMessage::RestoredRoom(room) => {
620                        server.restore_room(room)
621                    }
622                },
623                Err(e) => Weechat::print(&format!("Ruma error {}", e)),
624            };
625        }
626    }
627
628    /// Send loop that waits for requests that need to be sent out using our
629    /// Matrix client.
630    pub async fn send_loop(client: Client, channel: Receiver<ServerMessage>) {
631        while let Ok(message) = channel.recv().await {
632            match message {
633                ServerMessage::RoomSend(room_id, message) => {
634                    let content =
635                        MessageEventContent::Text(TextMessageEventContent {
636                            body: message,
637                            format: None,
638                            formatted_body: None,
639                            relates_to: None,
640                        });
641
642                    // TODO awaiting here means we can only send one message
643                    // at a time, we need to spawn a task here and return a
644                    // oneshot channel that the caller can await.
645                    // TODO the room should remember the UUID for the local echo
646                    // implementation.
647                    let ret = client
648                        .room_send(&room_id, content, Some(Uuid::new_v4()))
649                        .await;
650
651                    match ret {
652                        Ok(_r) => (),
653                        Err(_e) => (),
654                    }
655                }
656            }
657        }
658    }
659}
660
661impl Drop for MatrixServer {
662    fn drop(&mut self) {
663        // TODO close all the server buffers.
664        let config = &self.inner.borrow().config;
665        let mut config_borrow = config.borrow_mut();
666
667        let mut section = config_borrow
668            .search_section_mut("server")
669            .expect("Can't get server section");
670
671        for option_name in &["homeserver", "autoconnect"] {
672            let option_name = &format!("{}.{}", self.name(), option_name);
673            section.free_option(option_name).unwrap_or_else(|_| {
674                panic!(format!("Can't free option {}", option_name))
675            });
676        }
677    }
678}
679
680impl InnerServer {
681    pub(crate) fn get_or_create_room(
682        &mut self,
683        room_id: &RoomId,
684    ) -> &mut RoomBuffer {
685        if !self.room_buffers.contains_key(room_id) {
686            let homeserver = self
687                .settings
688                .homeserver
689                .as_ref()
690                .expect("Creating room buffer while no homeserver");
691            let login_state = self
692                .login_state
693                .as_ref()
694                .expect("Receiving events while not being logged in");
695            let buffer = RoomBuffer::new(
696                &self.server_name,
697                &self.connected_state,
698                homeserver,
699                room_id.clone(),
700                &login_state.user_id,
701            );
702            self.room_buffers.insert(room_id.clone(), buffer);
703        }
704
705        self.room_buffers.get_mut(room_id).unwrap()
706    }
707
708    pub fn room_buffers(&self) -> &HashMap<RoomId, RoomBuffer> {
709        &self.room_buffers
710    }
711
712    pub fn config(&self) -> Ref<Config> {
713        self.config.borrow()
714    }
715
716    fn restore_room(&mut self, room: Room) {
717        let homeserver = self
718            .settings
719            .homeserver
720            .as_ref()
721            .expect("Creating room buffer while no homeserver");
722
723        let room_id = room.room_id.clone();
724
725        let buffer = RoomBuffer::restore(
726            room,
727            &self.server_name,
728            &self.connected_state,
729            homeserver,
730        );
731
732        self.room_buffers.insert(room_id, buffer);
733    }
734
735    /// Is the server connected.
736    pub fn connected(&self) -> bool {
737        self.connected_state.borrow().is_some()
738    }
739
740    pub(crate) fn receive_joined_state_event(
741        &mut self,
742        room_id: &RoomId,
743        event: StateEvent,
744    ) {
745        let room = self.get_or_create_room(room_id);
746        room.handle_state_event(event)
747    }
748
749    pub(crate) fn receive_joined_timeline_event(
750        &mut self,
751        room_id: &RoomId,
752        event: RoomEvent,
753    ) {
754        let room = self.get_or_create_room(room_id);
755        room.handle_room_event(event)
756    }
757
758    pub fn receive_login(&mut self, response: LoginResponse) {
759        let login_state = LoginState {
760            user_id: response.user_id,
761        };
762        self.login_state = Some(login_state);
763    }
764
765    fn create_server_dir(&self) -> std::io::Result<()> {
766        let path = self.get_server_path();
767        std::fs::create_dir_all(path)
768    }
769
770    fn get_server_path(&self) -> PathBuf {
771        let mut path = Weechat::home_dir();
772        let server_name: &str = &self.server_name;
773        path.push("matrix-rust");
774        path.push(server_name);
775
776        path
777    }
778
779    pub fn create_client(&mut self) -> Result<Client, ServerError> {
780        let homeserver =
781            self.settings.homeserver.as_ref().ok_or_else(|| {
782                ServerError::StartError("Homeserver not configured".to_owned())
783            })?;
784
785        self.create_server_dir().map_err(|e| {
786            ServerError::IoError(format!(
787                "Error creating the session dir: {}",
788                e
789            ))
790        })?;
791
792        let mut client_config =
793            ClientConfig::new().store_path(self.get_server_path());
794
795        if let Some(proxy) = &self.settings.proxy {
796            client_config = client_config
797                .proxy(proxy.as_str())
798                .unwrap()
799                .disable_ssl_verification();
800        }
801
802        let client =
803            Client::new_with_config(homeserver.clone(), client_config).unwrap();
804        self.client = Some(client.clone());
805        Ok(client)
806    }
807}