src/connection.rs

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

452 lines · 14052 bytes

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