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