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