Commit 9651c4c2dd

9651c4c2dd2a8794933deaf6ce74ce883877a323

parent: 6aa326c390

Unsigned

Damir Jelić <poljar@termina.org.uk> · 2020-09-05 18:42 UTC

server: Move the Connection struct and logic into a separate module.

Layout: unified · split

Cargo.lock +5 −5
@@ -876,7 +876,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
876[[package]] 876[[package]]
877name = "matrix-sdk" 877name = "matrix-sdk"
878version = "0.1.0" 878version = "0.1.0"
879source = "git+https://github.com/matrix-org/matrix-rust-sdk/#6c7dbb814bcec79b9b3292ac2743adf355d41c62" 879source = "git+https://github.com/matrix-org/matrix-rust-sdk/#34cdf31cc5e03e763e794c662ec239c452a74829"
880dependencies = [ 880dependencies = [
881 "async-trait 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", 881 "async-trait 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
882 "dashmap 3.11.10 (registry+https://github.com/rust-lang/crates.io-index)", 882 "dashmap 3.11.10 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -896,7 +896,7 @@ dependencies = [
896[[package]] 896[[package]]
897name = "matrix-sdk-base" 897name = "matrix-sdk-base"
898version = "0.1.0" 898version = "0.1.0"
899source = "git+https://github.com/matrix-org/matrix-rust-sdk/#6c7dbb814bcec79b9b3292ac2743adf355d41c62" 899source = "git+https://github.com/matrix-org/matrix-rust-sdk/#34cdf31cc5e03e763e794c662ec239c452a74829"
900dependencies = [ 900dependencies = [
901 "async-trait 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", 901 "async-trait 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
902 "matrix-sdk-common 0.1.0 (git+https://github.com/matrix-org/matrix-rust-sdk/)", 902 "matrix-sdk-common 0.1.0 (git+https://github.com/matrix-org/matrix-rust-sdk/)",
@@ -913,7 +913,7 @@ dependencies = [
913[[package]] 913[[package]]
914name = "matrix-sdk-common" 914name = "matrix-sdk-common"
915version = "0.1.0" 915version = "0.1.0"
916source = "git+https://github.com/matrix-org/matrix-rust-sdk/#6c7dbb814bcec79b9b3292ac2743adf355d41c62" 916source = "git+https://github.com/matrix-org/matrix-rust-sdk/#34cdf31cc5e03e763e794c662ec239c452a74829"
917dependencies = [ 917dependencies = [
918 "assign 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", 918 "assign 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
919 "futures-locks 0.5.1-pre (git+https://github.com/asomers/futures-locks)", 919 "futures-locks 0.5.1-pre (git+https://github.com/asomers/futures-locks)",
@@ -927,7 +927,7 @@ dependencies = [
927[[package]] 927[[package]]
928name = "matrix-sdk-common-macros" 928name = "matrix-sdk-common-macros"
929version = "0.1.0" 929version = "0.1.0"
930source = "git+https://github.com/matrix-org/matrix-rust-sdk/#6c7dbb814bcec79b9b3292ac2743adf355d41c62" 930source = "git+https://github.com/matrix-org/matrix-rust-sdk/#34cdf31cc5e03e763e794c662ec239c452a74829"
931dependencies = [ 931dependencies = [
932 "quote 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)", 932 "quote 1.0.7 (registry+https://github.com/rust-lang/crates.io-index)",
933 "syn 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", 933 "syn 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -936,7 +936,7 @@ dependencies = [
936[[package]] 936[[package]]
937name = "matrix-sdk-crypto" 937name = "matrix-sdk-crypto"
938version = "0.1.0" 938version = "0.1.0"
939source = "git+https://github.com/matrix-org/matrix-rust-sdk/#6c7dbb814bcec79b9b3292ac2743adf355d41c62" 939source = "git+https://github.com/matrix-org/matrix-rust-sdk/#34cdf31cc5e03e763e794c662ec239c452a74829"
940dependencies = [ 940dependencies = [
941 "async-trait 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", 941 "async-trait 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
942 "atomic 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", 942 "atomic 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
src/commands/devices.rs +7 −12
@@ -1,7 +1,4 @@
1use clap::{ 1use clap::{App as Argparse, AppSettings as ArgParseSettings, Arg, SubCommand};
2 App as Argparse, AppSettings as ArgParseSettings, Arg,
3 SubCommand,
4};
5 2
6use weechat::{ 3use weechat::{
7 buffer::Buffer, 4 buffer::Buffer,
@@ -55,12 +52,7 @@ impl DevicesCommand {
55} 52}
56 53
57impl CommandCallback for DevicesCommand { 54impl CommandCallback for DevicesCommand {
58 fn callback( 55 fn callback(&mut self, _: &Weechat, buffer: &Buffer, arguments: Args) {
59 &mut self,
60 _: &Weechat,
61 buffer: &Buffer,
62 arguments: Args,
63 ) {
64 let argparse = Argparse::new("devices") 56 let argparse = Argparse::new("devices")
65 .global_setting(ArgParseSettings::DisableHelpFlags) 57 .global_setting(ArgParseSettings::DisableHelpFlags)
66 .global_setting(ArgParseSettings::DisableVersion) 58 .global_setting(ArgParseSettings::DisableVersion)
@@ -79,7 +71,7 @@ impl CommandCallback for DevicesCommand {
79 SubCommand::with_name("set-name") 71 SubCommand::with_name("set-name")
80 .about("Set the human readable name of the given device") 72 .about("Set the human readable name of the given device")
81 .arg(Arg::with_name("device-id").required(true)) 73 .arg(Arg::with_name("device-id").required(true))
82 .arg(Arg::with_name("name").required(true)) 74 .arg(Arg::with_name("name").required(true)),
83 ); 75 );
84 76
85 let matches = match argparse.get_matches_from_safe(arguments) { 77 let matches = match argparse.get_matches_from_safe(arguments) {
@@ -99,7 +91,10 @@ impl CommandCallback for DevicesCommand {
99 91
100 match matches.subcommand() { 92 match matches.subcommand() {
101 ("list", _) => self.list(buffer), 93 ("list", _) => self.list(buffer),
102 _ => Weechat::print(&format!("{}Subcommand isn't implemented", Weechat::prefix("error"))), 94 _ => Weechat::print(&format!(
95 "{}Subcommand isn't implemented",
96 Weechat::prefix("error")
97 )),
103 } 98 }
104 } 99 }
105} 100}
src/commands/matrix.rs +1 −1
@@ -10,7 +10,7 @@ use weechat::{
10 Args, Weechat, 10 Args, Weechat,
11}; 11};
12 12
13use crate::{PLUGIN_NAME, config::ConfigHandle, MatrixServer, Servers}; 13use crate::{config::ConfigHandle, MatrixServer, Servers, PLUGIN_NAME};
14 14
15pub struct MatrixCommand { 15pub struct MatrixCommand {
16 servers: Servers, 16 servers: Servers,
src/connection.rs added +392
@@ -0,0 +1,392 @@
1use std::{cell::RefCell, path::PathBuf, rc::Weak, time::Duration};
2
3use async_std::sync::{channel as async_channel, Receiver, Sender};
4use tokio::runtime::Runtime;
5use tracing::error;
6use uuid::Uuid;
7
8pub use matrix_sdk::{
9 self,
10 api::r0::{
11 device::get_devices::Response as DevicesResponse,
12 message::send_message_event::Response as RoomSendResponse,
13 session::login::Response as LoginResponse,
14 typing::create_typing_event::{Response as TypingResponse, Typing},
15 },
16 events::{
17 room::message::{MessageEventContent, TextMessageEventContent},
18 AnyMessageEventContent, AnySyncRoomEvent, AnySyncStateEvent,
19 },
20 identifiers::{RoomId, UserId},
21 Client, ClientConfig, Result as MatrixResult, Room, SyncSettings,
22};
23
24use weechat::{JoinHandle, Weechat};
25
26use crate::server::{InnerServer, MatrixServer};
27
28const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
29pub const TYPING_NOTICE_TIMEOUT: Duration = Duration::from_secs(4);
30
31pub enum ClientMessage {
32 LoginMessage(LoginResponse),
33 SyncState(RoomId, AnySyncStateEvent),
34 SyncEvent(RoomId, AnySyncRoomEvent),
35 RestoredRoom(Room),
36}
37
38/// Struc representing an active connection to the homeserver.
39///
40/// Since the rust-sdk `Client` object uses reqwest for the HTTP client making
41/// requests requires the request to be made on a tokio runtime. The connection
42/// wraps the `Client` object and makes sure that requests are run on the
43/// runtime the `Connection` holds.
44///
45/// While this struct is alive a sync loop will be going on. To cancel the sync
46/// loop drop the object.
47pub struct Connection {
48 receiver_task: JoinHandle<(), ()>,
49 client: Client,
50 #[used]
51 runtime: Runtime,
52}
53
54impl Drop for Connection {
55 fn drop(&mut self) {
56 self.receiver_task.cancel();
57 }
58}
59
60impl Connection {
61 pub fn new(server: &MatrixServer, client: &Client) -> Self {
62 let (tx, rx) = async_channel(1000);
63
64 let server_name = server.name();
65
66 let receiver_task = Weechat::spawn(Connection::response_receiver(
67 rx,
68 server.clone_inner_weak(),
69 ));
70
71 let server = server.inner();
72
73 let runtime = Runtime::new().unwrap();
74
75 let settings = server.settings();
76
77 runtime.spawn(Connection::sync_loop(
78 client.clone(),
79 tx,
80 settings.username.to_string(),
81 settings.password.to_string(),
82 server_name.to_string(),
83 server.get_server_path(),
84 ));
85
86 Self {
87 client: client.clone(),
88 runtime,
89 receiver_task,
90 }
91 }
92
93 /// Send a message to the given room.
94 ///
95 /// # Arguments
96 ///
97 /// * `room_id` - The id of the room which the message should be sent to.
98 ///
99 /// * `message` - The message that should be sent to the room.
100 pub async fn send_message(
101 &self,
102 room_id: &RoomId,
103 message: String,
104 ) -> MatrixResult<RoomSendResponse> {
105 // FIXME accept AnyMessageEventContent here.
106 let room_id = room_id.to_owned();
107 let client = self.client.clone();
108
109 let handle = self
110 .runtime
111 .spawn(async move {
112 let content =
113 MessageEventContent::Text(TextMessageEventContent {
114 body: message,
115 formatted: None,
116 relates_to: None,
117 });
118
119 client
120 .room_send(
121 &room_id,
122 AnyMessageEventContent::RoomMessage(content),
123 Some(Uuid::new_v4()),
124 )
125 .await
126 })
127 .await;
128
129 match handle {
130 Ok(response) => response,
131 Err(e) => panic!("Tokio error while sending a message {:?}", e),
132 }
133 }
134
135 /// Get the list of our own devices.
136 pub async fn devices(&self) -> MatrixResult<DevicesResponse> {
137 let client = self.client.clone();
138 let handle = self
139 .runtime
140 .spawn(async move { client.devices().await })
141 .await;
142
143 match handle {
144 Ok(response) => response,
145 Err(e) => panic!("Tokio error while sending a message {:?}", e),
146 }
147 }
148
149 /// Set or reset a typing notice.
150 ///
151 /// # Arguments
152 ///
153 /// * `room_id` - The id of the room where the typing notice should be
154 /// active.
155 ///
156 /// * `typing` - Should we set or unset the typing notice.
157 pub async fn send_typing_notice(
158 &self,
159 room_id: &RoomId,
160 typing: bool,
161 ) -> MatrixResult<TypingResponse> {
162 let room_id = room_id.to_owned();
163 let client = self.client.clone();
164
165 let handle = self
166 .runtime
167 .spawn(async move {
168 let typing = if typing {
169 Typing::Yes(TYPING_NOTICE_TIMEOUT)
170 } else {
171 Typing::No
172 };
173
174 client.typing_notice(&room_id, typing).await
175 })
176 .await;
177
178 match handle {
179 Ok(response) => response,
180 Err(e) => panic!("Tokio error while sending a message {:?}", e),
181 }
182 }
183
184 fn save_device_id(
185 user_name: &str,
186 mut server_path: PathBuf,
187 response: &LoginResponse,
188 ) -> std::io::Result<()> {
189 server_path.push(user_name);
190 server_path.set_extension("device_id");
191 std::fs::write(&server_path, &response.device_id.to_string())
192 }
193
194 fn load_device_id(
195 user_name: &str,
196 mut server_path: PathBuf,
197 ) -> std::io::Result<Option<String>> {
198 server_path.push(user_name);
199 server_path.set_extension("device_id");
200
201 let device_id = std::fs::read_to_string(server_path);
202
203 if let Err(e) = device_id {
204 // A file not found error is ok, report the rest.
205 if e.kind() != std::io::ErrorKind::NotFound {
206 return Err(e);
207 }
208 return Ok(None);
209 };
210
211 let device_id = device_id.unwrap_or_default();
212
213 if device_id.is_empty() {
214 Ok(None)
215 } else {
216 Ok(Some(device_id))
217 }
218 }
219
220 /// Response receiver loop.
221 /// This runs on the main Weechat thread and listens for responses coming
222 /// from the client running in the tokio executor.
223 pub async fn response_receiver(
224 receiver: Receiver<Result<ClientMessage, String>>,
225 server: Weak<RefCell<InnerServer>>,
226 ) {
227 loop {
228 let ret = receiver.recv().await;
229
230 let server_cell = server
231 .upgrade()
232 .expect("Can't upgrade server in sync receiver");
233 let mut server = server_cell.borrow_mut();
234
235 let message = match ret {
236 Ok(m) => m,
237 Err(e) => {
238 server.print_error(&format!(
239 "Error receiving message: {:?}",
240 e
241 ));
242 return;
243 }
244 };
245
246 match message {
247 Ok(message) => match message {
248 ClientMessage::LoginMessage(r) => server.receive_login(r),
249 ClientMessage::SyncEvent(r, e) => {
250 server.receive_joined_timeline_event(&r, e)
251 }
252 ClientMessage::SyncState(r, e) => {
253 server.receive_joined_state_event(&r, e)
254 }
255 ClientMessage::RestoredRoom(room) => {
256 server.restore_room(room)
257 }
258 },
259 Err(e) => server.print_error(&format!("Ruma error {}", e)),
260 };
261 }
262 }
263
264 /// Main client sync loop.
265 /// This runs on the per server tokio executor.
266 /// It communicates with the main Weechat thread using a async channel.
267 pub async fn sync_loop(
268 client: Client,
269 channel: Sender<Result<ClientMessage, String>>,
270 username: String,
271 password: String,
272 server_name: String,
273 server_path: PathBuf,
274 ) {
275 if !client.logged_in().await {
276 let device_id =
277 Connection::load_device_id(&username, server_path.clone());
278
279 let device_id = match device_id {
280 Err(e) => {
281 channel
282 .send(Err(format!(
283 "Error while reading the device id for server {}: {:?}",
284 server_name, e
285 )))
286 .await;
287 return;
288 }
289 Ok(d) => d,
290 };
291
292 let first_login = device_id.is_none();
293
294 let ret = client
295 .login(
296 &username,
297 &password,
298 device_id.as_deref(),
299 Some("Weechat-Matrix-rs"),
300 )
301 .await;
302
303 match ret {
304 Ok(response) => {
305 if let Err(e) = Connection::save_device_id(
306 &username,
307 server_path.clone(),
308 &response,
309 ) {
310 channel
311 .send(Err(format!(
312 "Error while writing the device id for server {}: {:?}",
313 server_name, e
314 ))).await;
315 return;
316 }
317
318 channel
319 .send(Ok(ClientMessage::LoginMessage(response)))
320 .await
321 }
322 Err(e) => {
323 channel
324 .send(Err(format!("Failed to log in: {:?}", e)))
325 .await;
326 return;
327 }
328 }
329
330 if !first_login {
331 let joined_rooms = client.joined_rooms();
332 for room in joined_rooms.read().await.values() {
333 let room = room.read().await;
334 let room: &Room = &*room;
335 channel
336 .send(Ok(ClientMessage::RestoredRoom(room.clone())))
337 .await
338 }
339 }
340 }
341
342 let sync_token = client.sync_token().await;
343 let sync_settings = SyncSettings::new().timeout(DEFAULT_SYNC_TIMEOUT);
344
345 let sync_settings = if let Some(t) = sync_token {
346 sync_settings.token(t)
347 } else {
348 sync_settings
349 };
350
351 let sync_channel = &channel;
352
353 client
354 .sync_forever(sync_settings, async move |response| {
355 let channel = sync_channel;
356
357 for (room_id, room) in response.rooms.join {
358 for event in room.state.events {
359 if let Ok(e) = event.deserialize() {
360 channel
361 .send(Ok(ClientMessage::SyncState(
362 room_id.clone(),
363 e,
364 )))
365 .await;
366 } else {
367 error!(
368 "Failed deserializing state event: {:#?}",
369 event
370 );
371 }
372 }
373 for event in room.timeline.events {
374 if let Ok(e) = event.deserialize() {
375 channel
376 .send(Ok(ClientMessage::SyncEvent(
377 room_id.clone(),
378 e,
379 )))
380 .await;
381 } else {
382 error!(
383 "Failed deserializing timeline event: {:#?}",
384 event
385 );
386 }
387 }
388 }
389 })
390 .await;
391 }
392}
src/lib.rs +1
@@ -2,6 +2,7 @@
2 2
3mod commands; 3mod commands;
4mod config; 4mod config;
5mod connection;
5mod debug; 6mod debug;
6mod render; 7mod render;
7mod room_buffer; 8mod room_buffer;
src/room_buffer.rs +4 −5
@@ -47,8 +47,8 @@ use async_trait::async_trait;
47use tracing::{debug, error, trace}; 47use tracing::{debug, error, trace};
48 48
49use crate::{ 49use crate::{
50 connection::{Connection, TYPING_NOTICE_TIMEOUT},
50 render::{render_membership, render_message}, 51 render::{render_membership, render_message},
51 server::{Connection, TYPING_NOTICE_TIMEOUT},
52}; 52};
53use std::{ 53use std::{
54 cell::{Ref, RefCell, RefMut}, 54 cell::{Ref, RefCell, RefMut},
@@ -106,6 +106,7 @@ impl BufferInputCallbackAsync for MatrixRoom {
106 async fn callback(&mut self, buffer: BufferHandle, input: String) { 106 async fn callback(&mut self, buffer: BufferHandle, input: String) {
107 let connection = &self.connection; 107 let connection = &self.connection;
108 108
109 // FIXME move this logic into the `MatrixRoom`
109 if let Some(c) = &*connection.borrow() { 110 if let Some(c) = &*connection.borrow() {
110 // TODO check for errors and print them out. 111 // TODO check for errors and print them out.
111 match c.send_message(&self.room_id, input).await { 112 match c.send_message(&self.room_id, input).await {
@@ -401,16 +402,14 @@ impl RoomBuffer {
401 402
402 let connection = self.inner.connection.clone(); 403 let connection = self.inner.connection.clone();
403 let room_id = self.room_id.clone(); 404 let room_id = self.room_id.clone();
404 let user_id = self.own_user_id.clone();
405 let typing_notice_time = self.inner.typing_notice_time.clone(); 405 let typing_notice_time = self.inner.typing_notice_time.clone();
406 406
407 let send = async move |typing: bool, _guard| { 407 let send = async move |typing: bool, _guard| {
408 let typing_time = typing_notice_time; 408 let typing_time = typing_notice_time;
409 409
410 if let Some(connection) = &*connection.borrow() { 410 if let Some(connection) = &*connection.borrow() {
411 let response = connection 411 let response =
412 .send_typing_notice(&*room_id, &*user_id, typing) 412 connection.send_typing_notice(&*room_id, typing).await;
413 .await;
414 413
415 // We need to record the time when the last typing notice was 414 // We need to record the time when the last typing notice was
416 // sent to ensure we don't send out new ones while a previous 415 // sent to ensure we don't send out new ones while a previous
src/server.rs +53 −376
@@ -54,7 +54,6 @@
54//! receiver fetches events individually from a mpsc channel. This makes sure 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. 55//! that processing events will not block the Weechat mainloop for too long.
56 56
57use async_std::sync::{channel as async_channel, Receiver, Sender};
58use chrono::{offset::Utc, DateTime}; 57use chrono::{offset::Utc, DateTime};
59use indoc::indoc; 58use indoc::indoc;
60use std::{ 59use std::{
@@ -62,47 +61,27 @@ use std::{
62 collections::HashMap, 61 collections::HashMap,
63 path::PathBuf, 62 path::PathBuf,
64 rc::{Rc, Weak}, 63 rc::{Rc, Weak},
65 time::Duration,
66}; 64};
67use tokio::runtime::Runtime;
68use tracing::error;
69use url::Url; 65use url::Url;
70use uuid::Uuid;
71
72use matrix_sdk::api::r0::session::login::Response as LoginResponse;
73 66
74use matrix_sdk::{ 67use matrix_sdk::{
75 self, 68 self,
76 api::r0::{ 69 api::r0::session::login::Response as LoginResponse,
77 device::get_devices::Response as DevicesResponse, 70 events::{AnySyncRoomEvent, AnySyncStateEvent},
78 message::send_message_event::Response as RoomSendResponse,
79 typing::create_typing_event::{Response as TypingResponse, Typing},
80 },
81 events::{
82 room::message::{MessageEventContent, TextMessageEventContent},
83 AnyMessageEventContent, AnySyncRoomEvent, AnySyncStateEvent,
84 },
85 identifiers::{RoomId, UserId}, 71 identifiers::{RoomId, UserId},
86 Client, ClientConfig, Result as MatrixResult, Room, SyncSettings, 72 Client, ClientConfig, Room,
87}; 73};
88 74
89use weechat::{ 75use weechat::{
90 buffer::{BufferBuilder, BufferHandle}, 76 buffer::{BufferBuilder, BufferHandle},
91 config::{BooleanOptionSettings, ConfigSection, StringOptionSettings}, 77 config::{BooleanOptionSettings, ConfigSection, StringOptionSettings},
92 JoinHandle, Weechat, 78 Weechat,
93}; 79};
94 80
95use crate::{config::Config, room_buffer::RoomBuffer, ConfigHandle}; 81use crate::{
96 82 config::Config, connection::Connection, room_buffer::RoomBuffer,
97const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30); 83 ConfigHandle,
98pub const TYPING_NOTICE_TIMEOUT: Duration = Duration::from_secs(4); 84};
99
100pub enum ClientMessage {
101 LoginMessage(LoginResponse),
102 SyncState(RoomId, AnySyncStateEvent),
103 SyncEvent(RoomId, AnySyncRoomEvent),
104 RestoredRoom(Room),
105}
106 85
107#[derive(Debug)] 86#[derive(Debug)]
108pub enum ServerError { 87pub enum ServerError {
@@ -112,11 +91,11 @@ pub enum ServerError {
112 91
113#[derive(Default)] 92#[derive(Default)]
114pub struct ServerSettings { 93pub struct ServerSettings {
115 homeserver: Option<Url>, 94 pub homeserver: Option<Url>,
116 proxy: Option<Url>, 95 pub proxy: Option<Url>,
117 autoconnect: bool, 96 pub autoconnect: bool,
118 username: String, 97 pub username: String,
119 password: String, 98 pub password: String,
120} 99}
121 100
122impl ServerSettings { 101impl ServerSettings {
@@ -129,91 +108,6 @@ pub struct LoginInfo {
129 user_id: UserId, 108 user_id: UserId,
130} 109}
131 110
132pub struct Connection {
133 response_receiver: JoinHandle<(), ()>,
134 client: Client,
135 #[used]
136 runtime: Runtime,
137}
138
139impl Connection {
140 pub async fn send_message(
141 &self,
142 room_id: &RoomId,
143 message: String,
144 ) -> MatrixResult<RoomSendResponse> {
145 let room_id = room_id.to_owned();
146 let client = self.client.clone();
147
148 let handle = self
149 .runtime
150 .spawn(async move {
151 let content =
152 MessageEventContent::Text(TextMessageEventContent {
153 body: message,
154 formatted: None,
155 relates_to: None,
156 });
157
158 client
159 .room_send(
160 &room_id,
161 AnyMessageEventContent::RoomMessage(content),
162 Some(Uuid::new_v4()),
163 )
164 .await
165 })
166 .await;
167
168 match handle {
169 Ok(response) => response,
170 Err(e) => panic!("Tokio error while sending a message {:?}", e),
171 }
172 }
173
174 pub async fn devices(&self) -> MatrixResult<DevicesResponse> {
175 let client = self.client.clone();
176 let handle = self
177 .runtime
178 .spawn(async move { client.devices().await })
179 .await;
180
181 match handle {
182 Ok(response) => response,
183 Err(e) => panic!("Tokio error while sending a message {:?}", e),
184 }
185 }
186
187 pub async fn send_typing_notice(
188 &self,
189 room_id: &RoomId,
190 user_id: &UserId,
191 typing: bool,
192 ) -> MatrixResult<TypingResponse> {
193 let room_id = room_id.to_owned();
194 let user_id = user_id.to_owned();
195 let client = self.client.clone();
196
197 let handle = self
198 .runtime
199 .spawn(async move {
200 let typing = if typing {
201 Typing::Yes(TYPING_NOTICE_TIMEOUT)
202 } else {
203 Typing::No
204 };
205
206 client.typing_notice(&room_id, &user_id, typing).await
207 })
208 .await;
209
210 match handle {
211 Ok(response) => response,
212 Err(e) => panic!("Tokio error while sending a message {:?}", e),
213 }
214 }
215}
216
217#[derive(Clone)] 111#[derive(Clone)]
218pub struct MatrixServer { 112pub struct MatrixServer {
219 server_name: Rc<String>, 113 server_name: Rc<String>,
@@ -274,6 +168,10 @@ impl MatrixServer {
274 self.inner.borrow() 168 self.inner.borrow()
275 } 169 }
276 170
171 pub fn clone_inner_weak(&self) -> Weak<RefCell<InnerServer>> {
172 Rc::downgrade(&self.inner)
173 }
174
277 pub fn connection(&self) -> Rc<RefCell<Option<Connection>>> { 175 pub fn connection(&self) -> Rc<RefCell<Option<Connection>>> {
278 self.inner().connection.clone() 176 self.inner().connection.clone()
279 } 177 }
@@ -508,42 +406,6 @@ impl MatrixServer {
508 self.inner.borrow().settings.autoconnect 406 self.inner.borrow().settings.autoconnect
509 } 407 }
510 408
511 fn save_device_id(
512 user_name: &str,
513 mut server_path: PathBuf,
514 response: &LoginResponse,
515 ) -> std::io::Result<()> {
516 server_path.push(user_name);
517 server_path.set_extension("device_id");
518 std::fs::write(&server_path, &response.device_id.to_string())
519 }
520
521 fn load_device_id(
522 user_name: &str,
523 mut server_path: PathBuf,
524 ) -> std::io::Result<Option<String>> {
525 server_path.push(user_name);
526 server_path.set_extension("device_id");
527
528 let device_id = std::fs::read_to_string(server_path);
529
530 if let Err(e) = device_id {
531 // A file not found error is ok, report the rest.
532 if e.kind() != std::io::ErrorKind::NotFound {
533 return Err(e);
534 }
535 return Ok(None);
536 };
537
538 let device_id = device_id.unwrap_or_default();
539
540 if device_id.is_empty() {
541 Ok(None)
542 } else {
543 Ok(Some(device_id))
544 }
545 }
546
547 pub fn connect(&self) -> Result<(), ServerError> { 409 pub fn connect(&self) -> Result<(), ServerError> {
548 if self.connected() { 410 if self.connected() {
549 self.print_error(&format!( 411 self.print_error(&format!(
@@ -556,49 +418,12 @@ impl MatrixServer {
556 return Ok(()); 418 return Ok(());
557 } 419 }
558 420
559 let runtime = Runtime::new().unwrap(); 421 let client = self.inner.borrow_mut().get_or_creaet_client()?;
560 let mut server = self.inner.borrow_mut(); 422 let connection = Connection::new(&self, &client);
561
562 let client = if let Some(c) = server.client.as_ref() {
563 c.clone()
564 } else {
565 server.create_client()?
566 };
567
568 // Check if the homeserver setting changed and swap our client if it
569 // did.
570 let client = if client.homeserver()
571 != server.settings.homeserver.as_ref().unwrap()
572 {
573 // TODO close all the room buffers of the server here, they don't
574 // belong to our client anymore.
575 server.create_client()?
576 } else {
577 client
578 };
579 423
580 let (tx, rx) = async_channel(1000); 424 *self.inner.borrow_mut().connection.borrow_mut() = Some(connection);
581 runtime.spawn(MatrixServer::sync_loop(
582 client.clone(),
583 tx,
584 server.settings.username.to_string(),
585 server.settings.password.to_string(),
586 server.server_name.to_string(),
587 server.get_server_path(),
588 ));
589 let response_receiver = Weechat::spawn(
590 MatrixServer::response_receiver(rx, Rc::downgrade(&self.inner)),
591 );
592 425
593 let mut connection = server.connection.borrow_mut(); 426 self.print_network(&format!(
594
595 *connection = Some(Connection {
596 client,
597 response_receiver,
598 runtime,
599 });
600
601 server.print_network(&format!(
602 "Connected to {}{}{}", 427 "Connected to {}{}{}",
603 Weechat::color("chat_server"), 428 Weechat::color("chat_server"),
604 self.name(), 429 self.name(),
@@ -639,11 +464,7 @@ impl MatrixServer {
639 { 464 {
640 let server = self.inner(); 465 let server = self.inner();
641 let mut connection = server.connection.borrow_mut(); 466 let mut connection = server.connection.borrow_mut();
642 let state = connection.take(); 467 connection.take();
643
644 if let Some(s) = state {
645 s.response_receiver.cancel();
646 }
647 } 468 }
648 469
649 self.print_network(&format!( 470 self.print_network(&format!(
@@ -654,179 +475,6 @@ impl MatrixServer {
654 )); 475 ));
655 } 476 }
656 477
657 /// Main client sync loop.
658 /// This runs on the per server tokio executor.
659 /// It communicates with the main Weechat thread using a async channel.
660 pub async fn sync_loop(
661 client: Client,
662 channel: Sender<Result<ClientMessage, String>>,
663 username: String,
664 password: String,
665 server_name: String,
666 server_path: PathBuf,
667 ) {
668 if !client.logged_in().await {
669 let device_id =
670 MatrixServer::load_device_id(&username, server_path.clone());
671
672 let device_id = match device_id {
673 Err(e) => {
674 channel
675 .send(Err(format!(
676 "Error while reading the device id for server {}: {:?}",
677 server_name, e
678 )))
679 .await;
680 return;
681 }
682 Ok(d) => d,
683 };
684
685 let first_login = device_id.is_none();
686
687 let ret = client
688 .login(
689 &username,
690 &password,
691 device_id.as_deref(),
692 Some("Weechat-Matrix-rs"),
693 )
694 .await;
695
696 match ret {
697 Ok(response) => {
698 if let Err(e) = MatrixServer::save_device_id(
699 &username,
700 server_path.clone(),
701 &response,
702 ) {
703 channel
704 .send(Err(format!(
705 "Error while writing the device id for server {}: {:?}",
706 server_name, e
707 ))).await;
708 return;
709 }
710
711 channel
712 .send(Ok(ClientMessage::LoginMessage(response)))
713 .await
714 }
715 Err(e) => {
716 channel
717 .send(Err(format!("Failed to log in: {:?}", e)))
718 .await;
719 return;
720 }
721 }
722
723 if !first_login {
724 let joined_rooms = client.joined_rooms();
725 for room in joined_rooms.read().await.values() {
726 let room = room.read().await;
727 let room: &Room = &*room;
728 channel
729 .send(Ok(ClientMessage::RestoredRoom(room.clone())))
730 .await
731 }
732 }
733 }
734
735 let sync_token = client.sync_token().await;
736 let sync_settings = SyncSettings::new().timeout(DEFAULT_SYNC_TIMEOUT);
737
738 let sync_settings = if let Some(t) = sync_token {
739 sync_settings.token(t)
740 } else {
741 sync_settings
742 };
743
744 let sync_channel = &channel;
745
746 client
747 .sync_forever(sync_settings, async move |response| {
748 let channel = sync_channel;
749
750 for (room_id, room) in response.rooms.join {
751 for event in room.state.events {
752 if let Ok(e) = event.deserialize() {
753 channel
754 .send(Ok(ClientMessage::SyncState(
755 room_id.clone(),
756 e,
757 )))
758 .await;
759 } else {
760 error!(
761 "Failed deserializing state event: {:#?}",
762 event
763 );
764 }
765 }
766 for event in room.timeline.events {
767 if let Ok(e) = event.deserialize() {
768 channel
769 .send(Ok(ClientMessage::SyncEvent(
770 room_id.clone(),
771 e,
772 )))
773 .await;
774 } else {
775 error!(
776 "Failed deserializing timeline event: {:#?}",
777 event
778 );
779 }
780 }
781 }
782 })
783 .await;
784 }
785
786 /// Response receiver loop.
787 /// This runs on the main Weechat thread and listens for responses coming
788 /// from the client running in the tokio executor.
789 pub async fn response_receiver(
790 receiver: Receiver<Result<ClientMessage, String>>,
791 server: Weak<RefCell<InnerServer>>,
792 ) {
793 loop {
794 let ret = receiver.recv().await;
795
796 let server_cell = server
797 .upgrade()
798 .expect("Can't upgrade server in sync receiver");
799 let mut server = server_cell.borrow_mut();
800
801 let message = match ret {
802 Ok(m) => m,
803 Err(e) => {
804 server.print_error(&format!(
805 "Error receiving message: {:?}",
806 e
807 ));
808 return;
809 }
810 };
811
812 match message {
813 Ok(message) => match message {
814 ClientMessage::LoginMessage(r) => server.receive_login(r),
815 ClientMessage::SyncEvent(r, e) => {
816 server.receive_joined_timeline_event(&r, e)
817 }
818 ClientMessage::SyncState(r, e) => {
819 server.receive_joined_state_event(&r, e)
820 }
821 ClientMessage::RestoredRoom(room) => {
822 server.restore_room(room)
823 }
824 },
825 Err(e) => server.print_error(&format!("Ruma error {}", e)),
826 };
827 }
828 }
829
830 pub fn get_info_str(&self, details: bool) -> String { 478 pub fn get_info_str(&self, details: bool) -> String {
831 let mut s = String::from(&format!( 479 let mut s = String::from(&format!(
832 "{}{}{} [{}]", 480 "{}{}{} [{}]",
@@ -914,6 +562,10 @@ impl InnerServer {
914 self.room_buffers.get_mut(room_id).unwrap() 562 self.room_buffers.get_mut(room_id).unwrap()
915 } 563 }
916 564
565 pub fn settings(&self) -> &ServerSettings {
566 &self.settings
567 }
568
917 pub fn room_buffers(&self) -> &HashMap<RoomId, RoomBuffer> { 569 pub fn room_buffers(&self) -> &HashMap<RoomId, RoomBuffer> {
918 &self.room_buffers 570 &self.room_buffers
919 } 571 }
@@ -922,7 +574,7 @@ impl InnerServer {
922 self.config.borrow() 574 self.config.borrow()
923 } 575 }
924 576
925 fn restore_room(&mut self, room: Room) { 577 pub fn restore_room(&mut self, room: Room) {
926 let homeserver = self 578 let homeserver = self
927 .settings 579 .settings
928 .homeserver 580 .homeserver
@@ -959,6 +611,30 @@ impl InnerServer {
959 buffer_handle 611 buffer_handle
960 } 612 }
961 613
614 fn get_or_creaet_client(&mut self) -> Result<Client, ServerError> {
615 let client = if let Some(c) = self.client.as_ref() {
616 c.clone()
617 } else {
618 self.create_client()?
619 };
620
621 // Check if the homeserver setting changed and swap our client if it
622 // did.
623 if client.homeserver()
624 != self
625 .settings
626 .homeserver
627 .as_ref()
628 .expect("Homeserver URL isn't set")
629 {
630 // TODO close all the room buffers of the server here, they don't
631 // belong to our client anymore.
632 self.create_client()
633 } else {
634 Ok(client)
635 }
636 }
637
962 /// Borrow the server buffer handle. 638 /// Borrow the server buffer handle.
963 pub fn server_buffer(&self) -> Ref<Option<BufferHandle>> { 639 pub fn server_buffer(&self) -> Ref<Option<BufferHandle>> {
964 self.server_buffer.borrow() 640 self.server_buffer.borrow()
@@ -1041,7 +717,7 @@ impl InnerServer {
1041 std::fs::create_dir_all(path) 717 std::fs::create_dir_all(path)
1042 } 718 }
1043 719
1044 fn get_server_path(&self) -> PathBuf { 720 pub fn get_server_path(&self) -> PathBuf {
1045 let mut path = Weechat::home_dir(); 721 let mut path = Weechat::home_dir();
1046 let server_name: &str = &self.server_name; 722 let server_name: &str = &self.server_name;
1047 path.push("matrix-rust"); 723 path.push("matrix-rust");
@@ -1076,6 +752,7 @@ impl InnerServer {
1076 let client = 752 let client =
1077 Client::new_with_config(homeserver.clone(), client_config).unwrap(); 753 Client::new_with_config(homeserver.clone(), client_config).unwrap();
1078 self.client = Some(client.clone()); 754 self.client = Some(client.clone());
755
1079 Ok(client) 756 Ok(client)
1080 } 757 }
1081} 758}