src/connection.rs

f930ae4023de7822cbf79eeddaebbd82235dcc98
weechat-matrix-rs/src/connection.rs history · blame · raw

389 lines · 12286 bytes

  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    /// * `content` - The content of the message that will be sent to the
100    /// server.
101    ///
102    /// * `transaction_id` - Attach an unique id to this message, later on the
103    /// event will contain the same id in the unsigned part of the event.
104    pub async fn send_message(
105        &self,
106        room_id: &RoomId,
107        content: AnyMessageEventContent,
108        transaction_id: Option<Uuid>,
109    ) -> MatrixResult<RoomSendResponse> {
110        let room_id = room_id.to_owned();
111        let client = self.client.clone();
112
113        let handle = self
114            .runtime
115            .spawn(async move {
116                client
117                    .room_send(
118                        &room_id,
119                        content,
120                        Some(transaction_id.unwrap_or_else(Uuid::new_v4)),
121                    )
122                    .await
123            })
124            .await;
125
126        match handle {
127            Ok(response) => response,
128            Err(e) => panic!("Tokio error while sending a message {:?}", e),
129        }
130    }
131
132    /// Get the list of our own devices.
133    pub async fn devices(&self) -> MatrixResult<DevicesResponse> {
134        let client = self.client.clone();
135        let handle = self
136            .runtime
137            .spawn(async move { client.devices().await })
138            .await;
139
140        match handle {
141            Ok(response) => response,
142            Err(e) => panic!("Tokio error while sending a message {:?}", e),
143        }
144    }
145
146    /// Set or reset a typing notice.
147    ///
148    /// # Arguments
149    ///
150    /// * `room_id` - The id of the room where the typing notice should be
151    /// active.
152    ///
153    /// * `typing` - Should we set or unset the typing notice.
154    pub async fn send_typing_notice(
155        &self,
156        room_id: &RoomId,
157        typing: bool,
158    ) -> MatrixResult<TypingResponse> {
159        let room_id = room_id.to_owned();
160        let client = self.client.clone();
161
162        let handle = self
163            .runtime
164            .spawn(async move {
165                let typing = if typing {
166                    Typing::Yes(TYPING_NOTICE_TIMEOUT)
167                } else {
168                    Typing::No
169                };
170
171                client.typing_notice(&room_id, typing).await
172            })
173            .await;
174
175        match handle {
176            Ok(response) => response,
177            Err(e) => panic!("Tokio error while sending a message {:?}", e),
178        }
179    }
180
181    fn save_device_id(
182        user_name: &str,
183        mut server_path: PathBuf,
184        response: &LoginResponse,
185    ) -> std::io::Result<()> {
186        server_path.push(user_name);
187        server_path.set_extension("device_id");
188        std::fs::write(&server_path, &response.device_id.to_string())
189    }
190
191    fn load_device_id(
192        user_name: &str,
193        mut server_path: PathBuf,
194    ) -> std::io::Result<Option<String>> {
195        server_path.push(user_name);
196        server_path.set_extension("device_id");
197
198        let device_id = std::fs::read_to_string(server_path);
199
200        if let Err(e) = device_id {
201            // A file not found error is ok, report the rest.
202            if e.kind() != std::io::ErrorKind::NotFound {
203                return Err(e);
204            }
205            return Ok(None);
206        };
207
208        let device_id = device_id.unwrap_or_default();
209
210        if device_id.is_empty() {
211            Ok(None)
212        } else {
213            Ok(Some(device_id))
214        }
215    }
216
217    /// Response receiver loop.
218    /// This runs on the main Weechat thread and listens for responses coming
219    /// from the client running in the tokio executor.
220    pub async fn response_receiver(
221        receiver: Receiver<Result<ClientMessage, String>>,
222        server: Weak<RefCell<InnerServer>>,
223    ) {
224        loop {
225            let ret = receiver.recv().await;
226
227            let server_cell = server
228                .upgrade()
229                .expect("Can't upgrade server in sync receiver");
230            let mut server = server_cell.borrow_mut();
231
232            let message = match ret {
233                Ok(m) => m,
234                Err(e) => {
235                    server.print_error(&format!(
236                        "Error receiving message: {:?}",
237                        e
238                    ));
239                    return;
240                }
241            };
242
243            match message {
244                Ok(message) => match message {
245                    ClientMessage::LoginMessage(r) => server.receive_login(r),
246                    ClientMessage::SyncEvent(r, e) => {
247                        server.receive_joined_timeline_event(&r, e)
248                    }
249                    ClientMessage::SyncState(r, e) => {
250                        server.receive_joined_state_event(&r, e)
251                    }
252                    ClientMessage::RestoredRoom(room) => {
253                        server.restore_room(room)
254                    }
255                },
256                Err(e) => server.print_error(&format!("Ruma error {}", e)),
257            };
258        }
259    }
260
261    /// Main client sync loop.
262    /// This runs on the per server tokio executor.
263    /// It communicates with the main Weechat thread using a async channel.
264    pub async fn sync_loop(
265        client: Client,
266        channel: Sender<Result<ClientMessage, String>>,
267        username: String,
268        password: String,
269        server_name: String,
270        server_path: PathBuf,
271    ) {
272        if !client.logged_in().await {
273            let device_id =
274                Connection::load_device_id(&username, server_path.clone());
275
276            let device_id = match device_id {
277                Err(e) => {
278                    channel
279                        .send(Err(format!(
280                        "Error while reading the device id for server {}: {:?}",
281                        server_name, e
282                    )))
283                        .await;
284                    return;
285                }
286                Ok(d) => d,
287            };
288
289            let first_login = device_id.is_none();
290
291            let ret = client
292                .login(
293                    &username,
294                    &password,
295                    device_id.as_deref(),
296                    Some("Weechat-Matrix-rs"),
297                )
298                .await;
299
300            match ret {
301                Ok(response) => {
302                    if let Err(e) = Connection::save_device_id(
303                        &username,
304                        server_path.clone(),
305                        &response,
306                    ) {
307                        channel
308                            .send(Err(format!(
309                            "Error while writing the device id for server {}: {:?}",
310                            server_name, e
311                        ))).await;
312                        return;
313                    }
314
315                    channel
316                        .send(Ok(ClientMessage::LoginMessage(response)))
317                        .await
318                }
319                Err(e) => {
320                    channel
321                        .send(Err(format!("Failed to log in: {:?}", e)))
322                        .await;
323                    return;
324                }
325            }
326
327            if !first_login {
328                let joined_rooms = client.joined_rooms();
329                for room in joined_rooms.read().await.values() {
330                    let room = room.read().await;
331                    let room: &Room = &*room;
332                    channel
333                        .send(Ok(ClientMessage::RestoredRoom(room.clone())))
334                        .await
335                }
336            }
337        }
338
339        let sync_token = client.sync_token().await;
340        let sync_settings = SyncSettings::new().timeout(DEFAULT_SYNC_TIMEOUT);
341
342        let sync_settings = if let Some(t) = sync_token {
343            sync_settings.token(t)
344        } else {
345            sync_settings
346        };
347
348        let sync_channel = &channel;
349
350        client
351            .sync_forever(sync_settings, async move |response| {
352                let channel = sync_channel;
353
354                for (room_id, room) in response.rooms.join {
355                    for event in room.state.events {
356                        if let Ok(e) = event.deserialize() {
357                            channel
358                                .send(Ok(ClientMessage::SyncState(
359                                    room_id.clone(),
360                                    e,
361                                )))
362                                .await;
363                        } else {
364                            error!(
365                                "Failed deserializing state event: {:#?}",
366                                event
367                            );
368                        }
369                    }
370                    for event in room.timeline.events {
371                        if let Ok(e) = event.deserialize() {
372                            channel
373                                .send(Ok(ClientMessage::SyncEvent(
374                                    room_id.clone(),
375                                    e,
376                                )))
377                                .await;
378                        } else {
379                            error!(
380                                "Failed deserializing timeline event: {:#?}",
381                                event
382                            );
383                        }
384                    }
385                }
386            })
387            .await;
388    }
389}