src/server.rs

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

664 lines · 21884 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.
 53use async_std::sync::channel as async_channel;
 54use async_std::sync::{Receiver, Sender};
 55use std::cell::RefCell;
 56use std::collections::HashMap;
 57use std::rc::{Rc, Weak};
 58use std::time::Duration;
 59use tokio::runtime::Runtime;
 60use url::Url;
 61use uuid::Uuid;
 62
 63use matrix_sdk::api::r0::session::login::Response as LoginResponse;
 64
 65use matrix_sdk::{
 66    self,
 67    events::{
 68        collections::all::{RoomEvent, StateEvent},
 69        room::message::{MessageEventContent, TextMessageEventContent},
 70        EventResult,
 71    },
 72    identifiers::{RoomId, UserId},
 73    AsyncClient, AsyncClientConfig, SyncSettings,
 74};
 75
 76use weechat::config::{
 77    BooleanOptionSettings, ConfigSection, StringOptionSettings,
 78};
 79use weechat::JoinHandle;
 80use weechat::Weechat;
 81
 82use crate::room_buffer::RoomBuffer;
 83use crate::Config;
 84use crate::PLUGIN_NAME;
 85
 86const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
 87
 88pub enum ThreadMessage {
 89    LoginMessage(LoginResponse),
 90    SyncState(RoomId, StateEvent),
 91    SyncEvent(RoomId, RoomEvent),
 92}
 93
 94#[derive(Debug)]
 95pub enum ServerError {
 96    StartError(String),
 97}
 98
 99pub enum ServerMessage {
100    RoomSend(RoomId, String),
101}
102
103#[derive(Default)]
104pub struct ServerSettings {
105    homeserver: Option<Url>,
106    proxy: Option<Url>,
107    autoconnect: bool,
108    username: String,
109    password: String,
110}
111
112impl ServerSettings {
113    pub fn new() -> Self {
114        Default::default()
115    }
116}
117
118pub struct LoginState {
119    user_id: UserId,
120    device_id: String,
121}
122
123pub struct Connection {
124    client_channel: Sender<ServerMessage>,
125    response_receiver: JoinHandle<(), ()>,
126    // TODO move the runtime into the plugin, once we're able to cancel tokio
127    // tasks.
128    runtime: Runtime,
129}
130
131impl Connection {
132    pub async fn send_message(&self, room_id: &RoomId, message: &str) {
133        self.client_channel
134            .send(ServerMessage::RoomSend(
135                room_id.to_owned(),
136                message.to_owned(),
137            ))
138            .await;
139    }
140}
141
142#[derive(Clone)]
143pub(crate) struct MatrixServer {
144    server_name: Rc<String>,
145    inner: Rc<RefCell<InnerServer>>,
146}
147
148pub(crate) struct InnerServer {
149    server_name: Rc<String>,
150    room_buffers: HashMap<RoomId, RoomBuffer>,
151    settings: ServerSettings,
152    config: Config,
153    client: Option<AsyncClient>,
154    login_state: Option<LoginState>,
155    connected_state: Rc<RefCell<Option<Connection>>>,
156}
157
158impl MatrixServer {
159    pub fn new(
160        name: &str,
161        config: &Config,
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            room_buffers: HashMap::new(),
169            settings: ServerSettings::new(),
170            config: config.clone(),
171            client: None,
172            login_state: None,
173            connected_state: Rc::new(RefCell::new(None)),
174        };
175
176        let server = Rc::new(RefCell::new(server));
177        MatrixServer::create_server_conf(&server_name, server_section, &server);
178
179        MatrixServer {
180            server_name,
181            inner: server,
182        }
183    }
184
185    pub fn name(&self) -> &str {
186        &self.server_name
187    }
188
189    pub fn parse_homeserver_url(value: String) -> Result<(), String> {
190        let url = Url::parse(&value);
191
192        match url {
193            Ok(u) => {
194                if u.cannot_be_a_base() {
195                    Err(String::from("The Homeserver URL is missing a schema"))
196                } else {
197                    Ok(())
198                }
199            }
200            Err(e) => Err(e.to_string()),
201        }
202    }
203
204    fn create_server_conf(
205        server_name: &str,
206        server_section: &mut ConfigSection,
207        server_ref: &Rc<RefCell<InnerServer>>,
208    ) {
209        let server = Rc::downgrade(server_ref);
210        let server_copy = server.clone();
211        let autoconnect =
212            BooleanOptionSettings::new(format!("{}.autoconnect", server_name))
213                .set_change_callback(move |_, option| {
214                    let server = server.clone();
215                    let value = option.value();
216
217                    let server_ref = server.upgrade().expect(
218                        "Server got deleted while server config is alive",
219                    );
220
221                    let mut server = server_ref.borrow_mut();
222                    server.settings.autoconnect = value;
223                });
224
225        server_section
226            .new_boolean_option(autoconnect)
227            .expect("Can't create autoconnect option");
228
229        let server = server_copy;
230        let server_copy = server.clone();
231
232        let homeserver =
233            StringOptionSettings::new(format!("{}.homeserver", server_name))
234                .set_check_callback(|_, _, value| {
235                    if value.is_empty() {
236                        true
237                    } else {
238                        MatrixServer::parse_homeserver_url(value.to_string())
239                            .is_ok()
240                    }
241                })
242                .set_change_callback(move |_, option| {
243                    let server = server.clone();
244                    let server_ref = server.upgrade().expect(
245                        "Server got deleted while server config is alive",
246                    );
247
248                    let mut server = server_ref.borrow_mut();
249                    let homeserver = Url::parse(option.value().as_ref()).expect(
250                "Can't parse homeserver URL, did the check callback fail?",
251                    );
252
253                    server.settings.homeserver = Some(homeserver)
254                });
255
256        server_section
257            .new_string_option(homeserver)
258            .expect("Can't create homeserver option");
259
260        let server = server_copy;
261        let server_copy = server.clone();
262
263        let proxy = StringOptionSettings::new(format!("{}.proxy", server_name))
264            .set_check_callback(|_, _, value| {
265                if value.is_empty() {
266                    true
267                } else {
268                    MatrixServer::parse_homeserver_url(value.to_string())
269                        .is_ok()
270                }
271            })
272            .set_change_callback(move |_, option| {
273                let server = server.clone();
274                let server_ref = server
275                    .upgrade()
276                    .expect("Server got deleted while server config is alive");
277
278                let mut server = server_ref.borrow_mut();
279                let proxy = Url::parse(option.value().as_ref()).expect(
280                    "Can't parse proxy URL, did the check callback fail?",
281                );
282
283                server.settings.proxy = Some(proxy)
284            });
285
286        server_section
287            .new_string_option(proxy)
288            .expect("Can't create proxy option");
289
290        let server = server_copy;
291        let server_copy = server.clone();
292
293        let username =
294            StringOptionSettings::new(format!("{}.username", server_name))
295                .set_change_callback(move |_, option| {
296                    let server = server.clone();
297
298                    let server_ref = server.upgrade().expect(
299                        "Server got deleted while server config is alive",
300                    );
301
302                    let mut server = server_ref.borrow_mut();
303                    server.settings.username = option.value().to_string();
304                });
305
306        server_section
307            .new_string_option(username)
308            .expect("Can't create username option");
309
310        let server = server_copy;
311
312        let password =
313            StringOptionSettings::new(format!("{}.password", server_name))
314                .set_change_callback(move |_, option| {
315                    let server = server.clone();
316
317                    let server_ref = server.upgrade().expect(
318                        "Server got deleted while server config is alive",
319                    );
320
321                    let mut server = server_ref.borrow_mut();
322                    server.settings.password = option.value().to_string();
323                });
324
325        server_section
326            .new_string_option(password)
327            .expect("Can't create password option");
328    }
329
330    pub fn connected(&self) -> bool {
331        self.inner.borrow().connected()
332    }
333
334    pub fn autoconnect(&self) -> bool {
335        self.inner.borrow().settings.autoconnect
336    }
337}
338
339impl Drop for MatrixServer {
340    fn drop(&mut self) {
341        // TODO close all the server buffers.
342        let config = &self.inner.borrow().config;
343        let mut config_borrow = config.borrow_mut();
344
345        let mut section = config_borrow
346            .search_section_mut("server")
347            .expect("Can't get server section");
348
349        for option_name in &["homeserver", "autoconnect"] {
350            let option_name = &format!("{}.{}", self.name(), option_name);
351            section.free_option(option_name).unwrap_or_else(|_| {
352                panic!(format!("Can't free option {}", option_name))
353            });
354        }
355    }
356}
357
358impl InnerServer {
359    pub(crate) fn get_or_create_room(
360        &mut self,
361        room_id: &RoomId,
362    ) -> &mut RoomBuffer {
363        if !self.room_buffers.contains_key(room_id) {
364            let homeserver = self
365                .settings
366                .homeserver
367                .as_ref()
368                .expect("Creating room buffer while no homeserver");
369            let login_state = self
370                .login_state
371                .as_ref()
372                .expect("Receiving events while not being logged in");
373            let buffer = RoomBuffer::new(
374                &self.server_name,
375                &self.connected_state,
376                homeserver,
377                &self.config,
378                room_id.clone(),
379                &login_state.user_id,
380            );
381            self.room_buffers.insert(room_id.clone(), buffer);
382        }
383
384        self.room_buffers.get_mut(room_id).unwrap()
385    }
386
387    /// Is the server connected.
388    pub fn connected(&self) -> bool {
389        self.connected_state.borrow().is_some()
390    }
391
392    pub(crate) fn receive_joined_state_event(
393        &mut self,
394        room_id: &RoomId,
395        event: StateEvent,
396    ) {
397        let room = self.get_or_create_room(room_id);
398        room.handle_state_event(event)
399    }
400
401    pub(crate) fn receive_joined_timeline_event(
402        &mut self,
403        room_id: &RoomId,
404        event: RoomEvent,
405    ) {
406        let room = self.get_or_create_room(room_id);
407        room.handle_room_event(event)
408    }
409
410    pub fn receive_login(&mut self, response: LoginResponse) {
411        let login_state = LoginState {
412            user_id: response.user_id,
413            device_id: response.device_id,
414        };
415        self.login_state = Some(login_state);
416    }
417
418    pub fn create_client(&mut self) -> Result<AsyncClient, ServerError> {
419        let homeserver =
420            self.settings.homeserver.as_ref().ok_or_else(|| {
421                ServerError::StartError("Homeserver not configured".to_owned())
422            })?;
423
424        let mut client_config = AsyncClientConfig::new();
425
426        if let Some(proxy) = &self.settings.proxy {
427            client_config = client_config
428                .proxy(proxy.as_str())
429                .unwrap()
430                .disable_ssl_verification();
431        }
432
433        let client = AsyncClient::new_with_config(
434            homeserver.clone(),
435            None,
436            client_config,
437        )
438        .unwrap();
439        self.client = Some(client.clone());
440        Ok(client)
441    }
442}
443
444impl MatrixServer {
445    pub fn connect(&self) -> Result<(), ServerError> {
446        if self.connected() {
447            return Ok(());
448        }
449
450        let runtime = Runtime::new().unwrap();
451        let mut server = self.inner.borrow_mut();
452
453        let client = if let Some(c) = server.client.as_ref() {
454            c.clone()
455        } else {
456            server.create_client()?
457        };
458
459        // Check if the homeserver setting changed and swap our client if it
460        // did.
461        let client = if client.homeserver()
462            != server.settings.homeserver.as_ref().unwrap()
463        {
464            // TODO close all the room buffers of the server here, they don't
465            // belong to our client anymore.
466            server.create_client()?
467        } else {
468            client
469        };
470
471        let (tx, rx) = async_channel(1000);
472        runtime.spawn(MatrixServer::sync_loop(
473            client.clone(),
474            tx,
475            server.settings.username.to_string(),
476            server.settings.password.to_string(),
477        ));
478        let response_receiver = Weechat::spawn(
479            MatrixServer::response_receiver(rx, Rc::downgrade(&self.inner)),
480        );
481
482        let (client_sender, client_receiver) = async_channel(10);
483        runtime.spawn(MatrixServer::send_loop(client, client_receiver));
484
485        let mut connected_state = server.connected_state.borrow_mut();
486
487        *connected_state = Some(Connection {
488            response_receiver,
489            client_channel: client_sender,
490            runtime,
491        });
492
493        Ok(())
494    }
495
496    pub fn disconnect(&self) {
497        // TODO these messages should go to the server buffer.
498        if !self.connected() {
499            Weechat::print(&format!(
500                "{}{}: Server {}{}{} is not connected.",
501                Weechat::prefix("error"),
502                PLUGIN_NAME,
503                Weechat::color("chat_server"),
504                self.name(),
505                Weechat::color("reset")
506            ));
507
508            return;
509        }
510
511        let server = self.inner.borrow_mut();
512        let mut connected_state = server.connected_state.borrow_mut();
513        let state = connected_state.take();
514
515        if let Some(s) = state {
516            s.response_receiver.cancel();
517        }
518
519        Weechat::print(&format!("{}: Disconnected from server.", PLUGIN_NAME));
520    }
521
522    /// Main client sync loop.
523    /// This runs on the per server tokio executor.
524    /// It communicates with the main Weechat thread using a async channel.
525    pub async fn sync_loop(
526        mut client: AsyncClient,
527        channel: Sender<Result<ThreadMessage, String>>,
528        username: String,
529        password: String,
530    ) {
531        if !client.logged_in().await {
532            let ret = client
533                .login(
534                    username,
535                    password,
536                    None,
537                    Some("Weechat-Matrix".to_owned()),
538                )
539                .await;
540
541            match ret {
542                Ok(response) => {
543                    channel
544                        .send(Ok(ThreadMessage::LoginMessage(response)))
545                        .await
546                }
547                Err(_e) => {
548                    channel.send(Err("No logging in".to_string())).await;
549                    return;
550                }
551            }
552        }
553
554        let sync_token = client.sync_token().await;
555        let sync_settings = SyncSettings::new().timeout(DEFAULT_SYNC_TIMEOUT);
556
557        let sync_settings = if let Some(t) = sync_token {
558            sync_settings.token(t)
559        } else {
560            sync_settings
561        };
562
563        let sync_channel = &channel;
564
565        client
566            .sync_forever(sync_settings, async move |response| {
567                let channel = sync_channel;
568                for (room_id, room) in response.rooms.join {
569                    for event in room.state.events {
570                        if let EventResult::Ok(e) = event {
571                            channel
572                                .send(Ok(ThreadMessage::SyncState(
573                                    room_id.clone(),
574                                    e,
575                                )))
576                                .await;
577                        }
578                    }
579                    for event in room.timeline.events {
580                        if let EventResult::Ok(e) = event {
581                            channel
582                                .send(Ok(ThreadMessage::SyncEvent(
583                                    room_id.clone(),
584                                    e,
585                                )))
586                                .await;
587                        }
588                    }
589                }
590            })
591            .await;
592    }
593
594    /// Response receiver loop.
595    /// This runs on the main Weechat thread and listens for responses coming
596    /// from the client running in the tokio executor.
597    pub async fn response_receiver(
598        receiver: Receiver<Result<ThreadMessage, String>>,
599        server: Weak<RefCell<InnerServer>>,
600    ) {
601        loop {
602            let ret = match receiver.recv().await {
603                Some(m) => m,
604                None => {
605                    Weechat::print("Error receiving message");
606                    return;
607                }
608            };
609
610            let server_cell = server
611                .upgrade()
612                .expect("Can't upgrade server in sync receiver");
613            let mut server = server_cell.borrow_mut();
614
615            match ret {
616                Ok(message) => match message {
617                    ThreadMessage::LoginMessage(r) => server.receive_login(r),
618                    ThreadMessage::SyncEvent(r, e) => {
619                        server.receive_joined_timeline_event(&r, e)
620                    }
621                    ThreadMessage::SyncState(r, e) => {
622                        server.receive_joined_state_event(&r, e)
623                    }
624                },
625                Err(e) => Weechat::print(&format!("Ruma error {}", e)),
626            };
627        }
628    }
629
630    /// Send loop that waits for requests that need to be sent out using our
631    /// Matrix client.
632    pub async fn send_loop(
633        mut client: AsyncClient,
634        channel: Receiver<ServerMessage>,
635    ) {
636        while let Some(message) = channel.recv().await {
637            match message {
638                ServerMessage::RoomSend(room_id, message) => {
639                    let content =
640                        MessageEventContent::Text(TextMessageEventContent {
641                            body: message,
642                            format: None,
643                            formatted_body: None,
644                            relates_to: None,
645                        });
646
647                    // TODO awaiting here means we can only send one message
648                    // at a time, we need to spawn a task here and return a
649                    // oneshot channel that the caller can await.
650                    // TODO the room should remember the UUID for the local echo
651                    // implementation.
652                    let ret = client
653                        .room_send(&room_id, content, Some(Uuid::new_v4()))
654                        .await;
655
656                    match ret {
657                        Ok(_r) => (),
658                        Err(_e) => (),
659                    }
660                }
661            }
662        }
663    }
664}