[fractal] API, room: use endpoint in get_message_context



commit 1e5c9d08edb58317d6f4f8b19f2208dece3807d1
Author: Alejandro Domínguez <adomu net-c com>
Date:   Tue Mar 3 20:57:34 2020 +0100

    API, room: use endpoint in get_message_context

 fractal-matrix-api/src/backend/mod.rs            | 17 ++++-
 fractal-matrix-api/src/backend/room.rs           | 85 ++++++++----------------
 fractal-matrix-api/src/r0.rs                     |  1 +
 fractal-matrix-api/src/r0/context.rs             |  1 +
 fractal-matrix-api/src/r0/context/get_context.rs | 51 ++++++++++++++
 5 files changed, 96 insertions(+), 59 deletions(-)
---
diff --git a/fractal-matrix-api/src/backend/mod.rs b/fractal-matrix-api/src/backend/mod.rs
index d83622cb..ab6bf9b5 100644
--- a/fractal-matrix-api/src/backend/mod.rs
+++ b/fractal-matrix-api/src/backend/mod.rs
@@ -17,6 +17,8 @@ use crate::cache::CacheMap;
 
 use crate::r0::AccessToken;
 
+use crate::globals;
+
 mod directory;
 mod media;
 pub mod register;
@@ -239,8 +241,19 @@ impl Backend {
                 room::get_room_messages_from_msg(self, server, access_token, room_id, from)
             }
             Ok(BKCommand::GetMessageContext(server, access_token, message)) => {
-                let r = room::get_message_context(self, server, access_token, message);
-                bkerror2!(r, tx, BKResponse::RoomMessagesTo);
+                thread::spawn(move || {
+                    let room_id = message.room.clone();
+                    let event_id = &message.id;
+                    let query = room::get_message_context(
+                        server,
+                        access_token,
+                        room_id,
+                        event_id,
+                        globals::PAGE_LIMIT as u64,
+                    );
+                    tx.send(BKResponse::RoomMessagesTo(query))
+                        .expect_log("Connection closed");
+                });
             }
             Ok(BKCommand::SendMsg(server, access_token, msg)) => {
                 let r = room::send_msg(self, server, access_token, msg);
diff --git a/fractal-matrix-api/src/backend/room.rs b/fractal-matrix-api/src/backend/room.rs
index b7de16f6..2138cf7a 100644
--- a/fractal-matrix-api/src/backend/room.rs
+++ b/fractal-matrix-api/src/backend/room.rs
@@ -3,7 +3,6 @@ use serde_json::json;
 
 use ruma_identifiers::{Error as IdError, RoomId, RoomIdOrAliasId, UserId};
 use std::fs;
-use std::sync::mpsc::Sender;
 use url::Url;
 
 use std::collections::HashMap;
@@ -16,7 +15,6 @@ use crate::globals;
 use std::thread;
 
 use crate::util::cache_dir_path;
-use crate::util::client_url;
 use crate::util::dw_media;
 use crate::util::get_prev_batch_from;
 use crate::util::json_q;
@@ -30,6 +28,9 @@ use crate::backend::types::Backend;
 use crate::backend::types::BackendData;
 use crate::backend::types::RoomType;
 
+use crate::r0::context::get_context::request as get_context;
+use crate::r0::context::get_context::Parameters as GetContextParameters;
+use crate::r0::context::get_context::Response as GetContextResponse;
 use crate::r0::filter::RoomEventFilter;
 use crate::r0::media::create::request as create_content;
 use crate::r0::media::create::Parameters as CreateContentParameters;
@@ -228,32 +229,32 @@ pub fn get_room_messages_from_msg(
     });
 }
 
-fn parse_context(
-    tx: Sender<BKResponse>,
-    tk: AccessToken,
-    baseu: Url,
+pub fn get_message_context(
+    base: Url,
+    access_token: AccessToken,
     room_id: RoomId,
     eid: &str,
-    limit: i32,
-) -> Result<(), Error> {
-    let url = client_url(
-        &baseu,
-        &format!("rooms/{}/context/{}", room_id, eid),
-        &[
-            ("limit", format!("{}", limit)),
-            ("access_token", tk.to_string()),
-        ],
-    )?;
+    limit: u64,
+) -> Result<(Vec<Message>, RoomId, Option<String>), Error> {
+    let params = GetContextParameters {
+        access_token: access_token.clone(),
+        limit,
+        filter: Default::default(),
+    };
+
+    get_context(base.clone(), &params, &room_id, eid)
+        .map_err(Into::into)
+        .and_then(|request| {
+            let response = HTTP_CLIENT
+                .get_client()?
+                .execute(request)?
+                .json::<GetContextResponse>()?;
 
-    get!(
-        url,
-        |response: JsonValue| {
             let mut id: Option<String> = None;
 
-            let ms: Result<Vec<Message>, _> = response["events_before"]
-                .as_array()
-                .into_iter()
-                .flatten()
+            let ms: Result<Vec<Message>, _> = response
+                .events_before
+                .iter()
                 .rev()
                 .inspect(|msg| {
                     if id.is_none() {
@@ -267,42 +268,12 @@ fn parse_context(
             match (ms, id) {
                 (Ok(msgs), Some(ref id)) if msgs.is_empty() => {
                     // there's no messages so we'll try with a bigger context
-                    if let Err(err) = parse_context(tx.clone(), tk, baseu, room_id, id, limit * 2) {
-                        tx.send(BKResponse::RoomMessagesTo(Err(err)))
-                            .expect_log("Connection closed");
-                    }
-                }
-                (Ok(msgs), _) => {
-                    tx.send(BKResponse::RoomMessagesTo(Ok((msgs, room_id, None))))
-                        .expect_log("Connection closed");
-                }
-                (Err(err), _) => {
-                    tx.send(BKResponse::RoomMessagesTo(Err(err.into())))
-                        .expect_log("Connection closed");
+                    get_message_context(base, access_token, room_id, id, limit * 2)
                 }
+                (Ok(msgs), _) => Ok((msgs, room_id, None)),
+                (Err(err), _) => Err(err.into()),
             }
-        },
-        |err| {
-            tx.send(BKResponse::RoomMessagesTo(Err(err)))
-                .expect_log("Connection closed");
-        }
-    );
-
-    Ok(())
-}
-
-pub fn get_message_context(
-    bk: &Backend,
-    baseu: Url,
-    tk: AccessToken,
-    msg: Message,
-) -> Result<(), Error> {
-    let tx = bk.tx.clone();
-    let room_id: RoomId = msg.room.clone();
-
-    parse_context(tx, tk, baseu, room_id, &msg.id, globals::PAGE_LIMIT)?;
-
-    Ok(())
+        })
 }
 
 pub fn send_msg(
diff --git a/fractal-matrix-api/src/r0.rs b/fractal-matrix-api/src/r0.rs
index 5988b554..8f6bc0fd 100644
--- a/fractal-matrix-api/src/r0.rs
+++ b/fractal-matrix-api/src/r0.rs
@@ -1,5 +1,6 @@
 pub mod account;
 pub mod contact;
+pub mod context;
 pub mod directory;
 pub mod filter;
 pub mod media;
diff --git a/fractal-matrix-api/src/r0/context.rs b/fractal-matrix-api/src/r0/context.rs
new file mode 100644
index 00000000..e2b1d939
--- /dev/null
+++ b/fractal-matrix-api/src/r0/context.rs
@@ -0,0 +1 @@
+pub mod get_context;
diff --git a/fractal-matrix-api/src/r0/context/get_context.rs 
b/fractal-matrix-api/src/r0/context/get_context.rs
new file mode 100644
index 00000000..04b43f63
--- /dev/null
+++ b/fractal-matrix-api/src/r0/context/get_context.rs
@@ -0,0 +1,51 @@
+use crate::r0::filter::serialize_room_event_filter_as_str;
+use crate::r0::filter::RoomEventFilter;
+use crate::r0::u64_is_10;
+use crate::r0::AccessToken;
+use reqwest::blocking::Client;
+use reqwest::blocking::Request;
+use reqwest::Error;
+use ruma_identifiers::RoomId;
+use serde::{Deserialize, Serialize};
+use serde_json::Value as JsonValue;
+use url::Url;
+
+#[derive(Clone, Debug, Serialize)]
+pub struct Parameters<'a> {
+    pub access_token: AccessToken,
+    #[serde(skip_serializing_if = "u64_is_10")]
+    pub limit: u64,
+    #[serde(serialize_with = "serialize_room_event_filter_as_str")]
+    #[serde(skip_serializing_if = "RoomEventFilter::is_default")]
+    pub filter: RoomEventFilter<'a>,
+}
+
+#[derive(Clone, Debug, Deserialize)]
+pub struct Response {
+    pub start: Option<String>,
+    pub end: Option<String>,
+    #[serde(default)]
+    pub events_before: Vec<JsonValue>,
+    #[serde(default)]
+    pub event: JsonValue,
+    #[serde(default)]
+    pub events_after: Vec<JsonValue>,
+    #[serde(default)]
+    pub state: Vec<JsonValue>,
+}
+
+pub fn request(
+    base: Url,
+    params: &Parameters,
+    room_id: &RoomId,
+    event_id: &str, // TODO: Use EventId
+) -> Result<Request, Error> {
+    let url = base
+        .join(&format!(
+            "/_matrix/client/r0/rooms/{}/context/{}",
+            room_id, event_id,
+        ))
+        .expect("Malformed URL in post_public_rooms");
+
+    Client::new().get(url).query(params).build()
+}


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]