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