src/connection.rs

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

385 lines · 12183 bytes

  1use std::{cell::RefCell, path::PathBuf, rc::Weak, sync::Arc, 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    locks::RwLock,
 22    Client, ClientConfig, LoopCtrl, Result as MatrixResult, Room, SyncSettings,
 23};
 24
 25use weechat::{Task, Weechat};
 26
 27use crate::server::{InnerServer, MatrixServer};
 28
 29const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
 30pub const TYPING_NOTICE_TIMEOUT: Duration = Duration::from_secs(4);
 31
 32pub enum ClientMessage {
 33    LoginMessage(LoginResponse),
 34    SyncState(RoomId, AnySyncStateEvent),
 35    SyncEvent(RoomId, AnySyncRoomEvent),
 36    RestoredRoom(Arc<RwLock<Room>>),
 37}
 38
 39/// Struc representing an active connection to the homeserver.
 40///
 41/// Since the rust-sdk `Client` object uses reqwest for the HTTP client making
 42/// requests requires the request to be made on a tokio runtime. The connection
 43/// wraps the `Client` object and makes sure that requests are run on the
 44/// runtime the `Connection` holds.
 45///
 46/// While this struct is alive a sync loop will be going on. To cancel the sync
 47/// loop drop the object.
 48pub struct Connection {
 49    #[used]
 50    receiver_task: Task<()>,
 51    client: Client,
 52    #[used]
 53    runtime: Runtime,
 54}
 55
 56impl Connection {
 57    pub fn new(server: &MatrixServer, client: &Client) -> Self {
 58        let (tx, rx) = async_channel(1000);
 59
 60        let server_name = server.name();
 61
 62        let receiver_task = Weechat::spawn(Connection::response_receiver(
 63            rx,
 64            server.clone_inner_weak(),
 65        ));
 66
 67        let server = server.inner();
 68
 69        let runtime = Runtime::new().unwrap();
 70
 71        let settings = server.settings();
 72
 73        runtime.spawn(Connection::sync_loop(
 74            client.clone(),
 75            tx,
 76            settings.username.to_string(),
 77            settings.password.to_string(),
 78            server_name.to_string(),
 79            server.get_server_path(),
 80        ));
 81
 82        Self {
 83            client: client.clone(),
 84            runtime,
 85            receiver_task,
 86        }
 87    }
 88
 89    /// Send a message to the given room.
 90    ///
 91    /// # Arguments
 92    ///
 93    /// * `room_id` - The id of the room which the message should be sent to.
 94    ///
 95    /// * `content` - The content of the message that will be sent to the
 96    /// server.
 97    ///
 98    /// * `transaction_id` - Attach an unique id to this message, later on the
 99    /// event will contain the same id in the unsigned part of the event.
100    pub async fn send_message(
101        &self,
102        room_id: &RoomId,
103        content: AnyMessageEventContent,
104        transaction_id: Option<Uuid>,
105    ) -> MatrixResult<RoomSendResponse> {
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                client
113                    .room_send(
114                        &room_id,
115                        content,
116                        Some(transaction_id.unwrap_or_else(Uuid::new_v4)),
117                    )
118                    .await
119            })
120            .await;
121
122        match handle {
123            Ok(response) => response,
124            Err(e) => panic!("Tokio error while sending a message {:?}", e),
125        }
126    }
127
128    /// Get the list of our own devices.
129    pub async fn devices(&self) -> MatrixResult<DevicesResponse> {
130        let client = self.client.clone();
131        let handle = self
132            .runtime
133            .spawn(async move { client.devices().await })
134            .await;
135
136        match handle {
137            Ok(response) => response,
138            Err(e) => panic!("Tokio error while sending a message {:?}", e),
139        }
140    }
141
142    /// Set or reset a typing notice.
143    ///
144    /// # Arguments
145    ///
146    /// * `room_id` - The id of the room where the typing notice should be
147    /// active.
148    ///
149    /// * `typing` - Should we set or unset the typing notice.
150    pub async fn send_typing_notice(
151        &self,
152        room_id: &RoomId,
153        typing: bool,
154    ) -> MatrixResult<TypingResponse> {
155        let room_id = room_id.to_owned();
156        let client = self.client.clone();
157
158        let handle = self
159            .runtime
160            .spawn(async move {
161                let typing = if typing {
162                    Typing::Yes(TYPING_NOTICE_TIMEOUT)
163                } else {
164                    Typing::No
165                };
166
167                client.typing_notice(&room_id, typing).await
168            })
169            .await;
170
171        match handle {
172            Ok(response) => response,
173            Err(e) => panic!("Tokio error while sending a message {:?}", e),
174        }
175    }
176
177    fn save_device_id(
178        user_name: &str,
179        mut server_path: PathBuf,
180        response: &LoginResponse,
181    ) -> std::io::Result<()> {
182        server_path.push(user_name);
183        server_path.set_extension("device_id");
184        std::fs::write(&server_path, &response.device_id.to_string())
185    }
186
187    fn load_device_id(
188        user_name: &str,
189        mut server_path: PathBuf,
190    ) -> std::io::Result<Option<String>> {
191        server_path.push(user_name);
192        server_path.set_extension("device_id");
193
194        let device_id = std::fs::read_to_string(server_path);
195
196        if let Err(e) = device_id {
197            // A file not found error is ok, report the rest.
198            if e.kind() != std::io::ErrorKind::NotFound {
199                return Err(e);
200            }
201            return Ok(None);
202        };
203
204        let device_id = device_id.unwrap_or_default();
205
206        if device_id.is_empty() {
207            Ok(None)
208        } else {
209            Ok(Some(device_id))
210        }
211    }
212
213    /// Response receiver loop.
214    /// This runs on the main Weechat thread and listens for responses coming
215    /// from the client running in the tokio executor.
216    pub async fn response_receiver(
217        receiver: Receiver<Result<ClientMessage, String>>,
218        server: Weak<RefCell<InnerServer>>,
219    ) {
220        loop {
221            let ret = receiver.recv().await;
222
223            let server_cell = server
224                .upgrade()
225                .expect("Can't upgrade server in sync receiver");
226            let mut server = server_cell.borrow_mut();
227
228            let message = match ret {
229                Ok(m) => m,
230                Err(e) => {
231                    server.print_error(&format!(
232                        "Error receiving message: {:?}",
233                        e
234                    ));
235                    return;
236                }
237            };
238
239            match message {
240                Ok(message) => match message {
241                    ClientMessage::LoginMessage(r) => server.receive_login(r),
242                    ClientMessage::SyncEvent(r, e) => {
243                        server.receive_joined_timeline_event(&r, e)
244                    }
245                    ClientMessage::SyncState(r, e) => {
246                        server.receive_joined_state_event(&r, e)
247                    }
248                    ClientMessage::RestoredRoom(room) => {
249                        server.restore_room(room)
250                    }
251                },
252                Err(e) => server.print_error(&format!("Ruma error {}", e)),
253            };
254        }
255    }
256
257    /// Main client sync loop.
258    /// This runs on the per server tokio executor.
259    /// It communicates with the main Weechat thread using a async channel.
260    pub async fn sync_loop(
261        client: Client,
262        channel: Sender<Result<ClientMessage, String>>,
263        username: String,
264        password: String,
265        server_name: String,
266        server_path: PathBuf,
267    ) {
268        if !client.logged_in().await {
269            let device_id =
270                Connection::load_device_id(&username, server_path.clone());
271
272            let device_id = match device_id {
273                Err(e) => {
274                    channel
275                        .send(Err(format!(
276                        "Error while reading the device id for server {}: {:?}",
277                        server_name, e
278                    )))
279                        .await;
280                    return;
281                }
282                Ok(d) => d,
283            };
284
285            let first_login = device_id.is_none();
286
287            let ret = client
288                .login(
289                    &username,
290                    &password,
291                    device_id.as_deref(),
292                    Some("Weechat-Matrix-rs"),
293                )
294                .await;
295
296            match ret {
297                Ok(response) => {
298                    if let Err(e) = Connection::save_device_id(
299                        &username,
300                        server_path.clone(),
301                        &response,
302                    ) {
303                        channel
304                            .send(Err(format!(
305                            "Error while writing the device id for server {}: {:?}",
306                            server_name, e
307                        ))).await;
308                        return;
309                    }
310
311                    channel
312                        .send(Ok(ClientMessage::LoginMessage(response)))
313                        .await
314                }
315                Err(e) => {
316                    channel
317                        .send(Err(format!("Failed to log in: {:?}", e)))
318                        .await;
319                    return;
320                }
321            }
322
323            if !first_login {
324                let joined_rooms = client.joined_rooms();
325                for room in joined_rooms.read().await.values() {
326                    channel
327                        .send(Ok(ClientMessage::RestoredRoom(room.clone())))
328                        .await
329                }
330            }
331        }
332
333        let sync_token = client.sync_token().await;
334        let sync_settings = SyncSettings::new().timeout(DEFAULT_SYNC_TIMEOUT);
335
336        let sync_settings = if let Some(t) = sync_token {
337            sync_settings.token(t)
338        } else {
339            sync_settings
340        };
341
342        let sync_channel = &channel;
343
344        client
345            .sync_with_callback(sync_settings, async move |response| {
346                let channel = sync_channel;
347
348                for (room_id, room) in response.rooms.join {
349                    for event in room.state.events {
350                        if let Ok(e) = event.deserialize() {
351                            channel
352                                .send(Ok(ClientMessage::SyncState(
353                                    room_id.clone(),
354                                    e,
355                                )))
356                                .await;
357                        } else {
358                            error!(
359                                "Failed deserializing state event: {:#?}",
360                                event
361                            );
362                        }
363                    }
364                    for event in room.timeline.events {
365                        if let Ok(e) = event.deserialize() {
366                            channel
367                                .send(Ok(ClientMessage::SyncEvent(
368                                    room_id.clone(),
369                                    e,
370                                )))
371                                .await;
372                        } else {
373                            error!(
374                                "Failed deserializing timeline event: {:#?}",
375                                event
376                            );
377                        }
378                    }
379                }
380
381                LoopCtrl::Continue
382            })
383            .await;
384    }
385}