From 3eef38c0fabba76216d548e3668f54a5f8549805 Mon Sep 17 00:00:00 2001
From: networkjanitor <networkjanitor@xafy.de>
Date: Thu, 18 Jul 2024 03:36:35 +0200
Subject: wip: redacted messages not handled yet

---
 src/matrix.rs | 57 ++++++++++++++++++++++++++++++---------------------------
 1 file changed, 30 insertions(+), 27 deletions(-)

diff --git a/src/matrix.rs b/src/matrix.rs
index cc6ba28..0b77b21 100644
--- a/src/matrix.rs
+++ b/src/matrix.rs
@@ -18,7 +18,6 @@ use matrix_sdk::{
     config::SyncSettings,
     matrix_auth::MatrixSession,
     ruma::{
-        api::client::message::get_message_events,
         api::client::filter::FilterDefinition,
         events::room::message::{RoomMessageEventContent, MessageType, Relation, ReplacementMetadata},
         events::{AnyMessageLikeEvent, AnyMessageLikeEventContent, AnyTimelineEvent},
@@ -27,6 +26,7 @@ use matrix_sdk::{
         MilliSecondsSinceUnixEpoch, UInt,
         RoomId, OwnedRoomId
     },
+    room::MessagesOptions,
     Client
 };
 
@@ -50,6 +50,7 @@ impl From<config::Matrix> for MatrixUser {
 }
 
 /// The data needed to re-build a client.
+/// Copied from the matrix-rust-sdk persist-session example.
 #[derive(Debug, Serialize, Deserialize)]
 struct ClientSession {
     /// The URL of the homeserver of the user.
@@ -63,6 +64,7 @@ struct ClientSession {
 }
 
 /// The full session to persist.
+/// Copied from the matrix-rust-sdk persist-session example.
 #[derive(Debug, Serialize, Deserialize)]
 struct FullSession {
     /// The data to re-build the client.
@@ -135,6 +137,7 @@ pub fn post_link(user: MatrixUser, room_id: &str, log: &Log, link: &str) -> Resu
 }
 
 /// Restore a previous session.
+/// Copied from the matrix-rust-sdk persist-session example.
 async fn restore_session(session_file: &Path) -> anyhow::Result<(Client, Option<String>)> {
     println!("Previous session found in '{}'", session_file.to_string_lossy());
 
@@ -159,6 +162,7 @@ async fn restore_session(session_file: &Path) -> anyhow::Result<(Client, Option<
 }
 
 /// Login with a new device.
+/// Copied from the matrix-rust-sdk persist-session example.
 async fn login(data_dir: &Path, session_file: &Path, homeserver: String, username: String, password: String) -> anyhow::Result<Client> {
     println!("No previous session found, logging in…");
 
@@ -201,6 +205,7 @@ async fn login(data_dir: &Path, session_file: &Path, homeserver: String, usernam
 }
 
 /// Build a new client.
+/// Copied from the matrix-rust-sdk persist-session example.
 async fn build_client(data_dir: &Path, homeserver: String) -> anyhow::Result<(Client, ClientSession)> {
     let mut rng = thread_rng();
 
@@ -244,6 +249,7 @@ async fn build_client(data_dir: &Path, homeserver: String) -> anyhow::Result<(Cl
 }
 
 /// Setup the client to listen to new messages.
+/// Copied from the matrix-rust-sdk persist-session example.
 async fn sync(
     client: &Client,
     initial_sync_token: Option<String>,
@@ -292,6 +298,7 @@ async fn sync(
 /// Persist the sync token for a future session.
 /// Note that this is needed only when using `sync_once`. Other sync methods get
 /// the sync token from the store.
+/// Copied from the matrix-rust-sdk persist-session example.
 async fn persist_sync_token(session_file: &Path, sync_token: String) -> anyhow::Result<()> {
     let serialized_session = fs::read_to_string(session_file).await?;
     let mut full_session: FullSession = serde_json::from_str(&serialized_session)?;
@@ -318,6 +325,7 @@ async fn find_message(
     )
     .expect("Our time limit is before the epoch");
     let mut continue_from = String::new();
+    let room = client.get_room(room_id).unwrap();
 
     for chunk_nr in 0..MESSAGE_CHUNK_COUNT {
         debug!(
@@ -327,41 +335,36 @@ async fn find_message(
             MESSAGE_CHUNK_COUNT
         );
 
-        let mut request = get_message_events::v3::Request::backward(room_id.clone()).from(continue_from);
-        request.limit = limit;
-        let response = client.send(request, None).await?;
-        for raw_message in response.chunk {
+        let mut options = MessagesOptions::backward().from(Some(continue_from).as_deref());
+        options.limit = limit;
+        let response = room.messages(options).await?;
+        for timeline_message in response.chunk {
             if let Ok(AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomMessage(msg))) =
-                raw_message.deserialize()
+                timeline_message.event.deserialize()
             {
-                debug!("my id: {:?}", my_id);
-                debug!("time limit: {:?}", time_limit);
                 if msg.sender() == my_id && msg.origin_server_ts() >= time_limit {
-                    // filters out redacted messages
+                    // filters out redacted messages - but apparently it doesn't?
+                    // maybe the sync is still wrong and doesn't 
                     if let Some(orig_msg) = &msg.as_original() {
-                        if let MessageType::Text(text) = &orig_msg.content.msgtype {
-                            if !matches!(
-                                orig_msg.content.relates_to,
-                                Some(Relation::Reply { .. } | Relation::Replacement(..))
-                            ) {
-                                return Ok(Some((orig_msg.event_id.to_owned(), text.body.clone())));
-                            } else {
-                                debug!("Rejected because of Relations: {:?}", msg);
-                            }
-                        } else {
-                            debug!("Rejected because of msgtype: {:?}", msg);
+                        match &orig_msg.content.relates_to {
+                            Some(relation) =>
+                                if let Relation::Replacement(replacement) = relation {
+                                    if let MessageType::Text(text) = &replacement.new_content.msgtype {
+                                        return Ok(Some((replacement.event_id.to_owned(), text.body.clone())));
+                                    }
+                                }
+                            None =>
+                                if let MessageType::Text(text) = &orig_msg.content.msgtype {
+                                    return Ok(Some((orig_msg.event_id.to_owned(), text.body.clone())));
+                                }
                         }
-                    } else {
-                        debug!("Rejected original message: {:?}", msg);
-                    }
-                } else {
-                    debug!("Rejected because of sender/time limit: {:?}", msg);
-                }
+                    } 
+                } 
             }
         }
 
         match response.end {
-            Some(token) => continue_from = token,
+            Some(token) => continue_from = String::from(token),
             None => break,
         }
     }
-- 
cgit v1.2.3