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