[fractal] API, room: use endpoint in update_direct_chats and direct_chat



commit e11ea2f9b25b5611179da299b46ac72bb65694b3
Author: Alejandro Domínguez <adomu net-c com>
Date:   Tue Mar 10 03:45:32 2020 +0100

    API, room: use endpoint in update_direct_chats and direct_chat

 fractal-matrix-api/src/backend/mod.rs              |  11 +-
 fractal-matrix-api/src/backend/room.rs             | 160 ++++++++++++---------
 fractal-matrix-api/src/r0.rs                       |   1 +
 fractal-matrix-api/src/r0/config.rs                |   2 +
 .../src/r0/config/get_global_account_data.rs       |  28 ++++
 .../src/r0/config/set_global_account_data.rs       |  30 ++++
 6 files changed, 157 insertions(+), 75 deletions(-)
---
diff --git a/fractal-matrix-api/src/backend/mod.rs b/fractal-matrix-api/src/backend/mod.rs
index 8d903e23..213127e0 100644
--- a/fractal-matrix-api/src/backend/mod.rs
+++ b/fractal-matrix-api/src/backend/mod.rs
@@ -338,12 +338,13 @@ impl Backend {
                 });
             }
             Ok(BKCommand::DirectChat(server, access_token, uid, user, internal_id)) => {
-                let r =
-                    room::direct_chat(self, server, access_token, uid, user, internal_id.clone());
-                if let Err(e) = r {
-                    tx.send(BKResponse::NewRoom(Err(e), internal_id))
+                let data = self.data.clone();
+
+                thread::spawn(move || {
+                    let room_res = room::direct_chat(data, server, access_token, uid, user);
+                    tx.send(BKResponse::NewRoom(room_res, internal_id))
                         .expect_log("Connection closed");
-                }
+                });
             }
             Ok(BKCommand::AddToFav(server, access_token, uid, room_id, tofav)) => {
                 thread::spawn(move || {
diff --git a/fractal-matrix-api/src/backend/room.rs b/fractal-matrix-api/src/backend/room.rs
index 1456e071..a429dd60 100644
--- a/fractal-matrix-api/src/backend/room.rs
+++ b/fractal-matrix-api/src/backend/room.rs
@@ -28,6 +28,10 @@ use crate::backend::types::Backend;
 use crate::backend::types::BackendData;
 use crate::backend::types::RoomType;
 
+use crate::r0::config::get_global_account_data::request as get_global_account_data;
+use crate::r0::config::get_global_account_data::Parameters as GetGlobalAccountDataParameters;
+use crate::r0::config::set_global_account_data::request as set_global_account_data;
+use crate::r0::config::set_global_account_data::Parameters as SetGlobalAccountDataParameters;
 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;
@@ -638,11 +642,27 @@ pub fn new_room(
         })
 }
 
-fn update_direct_chats(url: Url, data: Arc<Mutex<BackendData>>, user_id: UserId, room_id: RoomId) {
-    get!(
-        url.clone(),
-        |r: JsonValue| {
-            let directs: Result<HashMap<UserId, Vec<RoomId>>, IdError> = r
+fn update_direct_chats(
+    data: Arc<Mutex<BackendData>>,
+    base: Url,
+    access_token: AccessToken,
+    user_id: UserId,
+    room_id: RoomId,
+    user: Member,
+) {
+    let params = GetGlobalAccountDataParameters {
+        access_token: access_token.clone(),
+    };
+
+    let directs = get_global_account_data(base.clone(), &params, &user_id, "m.direct")
+        .map_err::<Error, _>(Into::into)
+        .and_then(|request| {
+            let response = HTTP_CLIENT
+                .get_client()?
+                .execute(request)?
+                .json::<JsonValue>()?;
+
+            response
                 .as_object()
                 .into_iter()
                 .flatten()
@@ -655,88 +675,88 @@ fn update_direct_chats(url: Url, data: Arc<Mutex<BackendData>>, user_id: UserId,
                         .collect::<Result<Vec<RoomId>, IdError>>()?;
                     Ok((UserId::try_from(uid.as_str())?, roomlist))
                 })
-                .collect();
-
-            if let Ok(mut directs) = directs {
-                if let Some(v) = directs.get_mut(&user_id) {
-                    v.push(room_id);
-                } else {
-                    directs.insert(user_id, vec![room_id]);
-                }
-                data.lock().unwrap().m_direct = directs.clone();
+                .collect::<Result<HashMap<UserId, Vec<RoomId>>, IdError>>()
+                .map_err(Into::into)
+        });
 
-                let attrs = json!(directs);
-                put!(url, &attrs, |_| {}, |err| error!("{:?}", err));
+    match directs {
+        Ok(mut directs) => {
+            if let Some(v) = directs.get_mut(&user.uid) {
+                v.push(room_id);
+            } else {
+                directs.insert(user.uid, vec![room_id]);
             }
-        },
-        |err| {
-            error!("Can't set m.direct: {:?}", err);
+            data.lock().unwrap().m_direct = directs.clone();
+
+            let params = SetGlobalAccountDataParameters {
+                access_token: access_token.clone(),
+            };
+
+            if let Err(err) =
+                set_global_account_data(base, &params, &json!(directs), &user_id, "m.direct")
+                    .map_err::<Error, _>(Into::into)
+                    .and_then(|request| {
+                        HTTP_CLIENT
+                            .get_client()?
+                            .execute(request)
+                            .map_err(Into::into)
+                    })
+            {
+                error!("{:?}", err);
+            };
         }
-    );
+        Err(err) => error!("Can't set m.direct: {:?}", err),
+    };
 }
 
 pub fn direct_chat(
-    bk: &Backend,
+    data: Arc<Mutex<BackendData>>,
     base: Url,
     access_token: AccessToken,
     user_id: UserId,
     user: Member,
-    internal_id: RoomId,
-) -> Result<(), Error> {
-    let url = bk.url(base.clone(), &access_token, "createRoom", vec![])?;
-    let attrs = json!({
-        "invite": [user.uid.clone()],
-        "invite_3pid": [],
-        "visibility": "private",
-        "preset": "private_chat",
-        "is_direct": true,
-        "state_event": {
+) -> Result<Room, Error> {
+    let params = CreateRoomParameters {
+        access_token: access_token.clone(),
+    };
+
+    let body = CreateRoomBody {
+        invite: vec![user.uid.clone()],
+        visibility: Some(Visibility::Private),
+        preset: Some(RoomPreset::PrivateChat),
+        is_direct: true,
+        initial_state: vec![json!({
             "type": "m.room.history_visibility",
             "content": {
                 "history_visibility": "invited"
             }
-        }
-    });
-
-    let direct_url = bk.url(
-        base,
-        &access_token,
-        &format!("user/{}/account_data/m.direct", user_id),
-        vec![],
-    )?;
+        })],
+        ..Default::default()
+    };
 
-    let tx = bk.tx.clone();
-    let data = bk.data.clone();
-    post!(
-        url,
-        &attrs,
-        move |r: JsonValue| {
-            match RoomId::try_from(r["room_id"].as_str().unwrap_or_default()) {
-                Ok(room_id) => {
-                    let r = Room {
-                        name: user.alias.clone(),
-                        direct: true,
-                        ..Room::new(room_id.clone(), RoomMembership::Joined(RoomTag::None))
-                    };
-
-                    tx.send(BKResponse::NewRoom(Ok(r), internal_id))
-                        .expect_log("Connection closed");
+    create_room(base.clone(), &params, &body)
+        .map_err(Into::into)
+        .and_then(|request| {
+            let response = HTTP_CLIENT
+                .get_client()?
+                .execute(request)?
+                .json::<CreateRoomResponse>()?;
 
-                    update_direct_chats(direct_url, data, user.uid.clone(), room_id);
-                }
-                Err(err) => {
-                    tx.send(BKResponse::NewRoom(Err(err.into()), internal_id))
-                        .expect_log("Connection closed");
-                }
-            }
-        },
-        |err| {
-            tx.send(BKResponse::NewRoom(Err(err), internal_id))
-                .expect_log("Connection closed");
-        }
-    );
+            update_direct_chats(
+                data,
+                base,
+                access_token,
+                user_id,
+                response.room_id.clone(),
+                user.clone(),
+            );
 
-    Ok(())
+            Ok(Room {
+                name: user.alias.clone(),
+                direct: true,
+                ..Room::new(response.room_id, RoomMembership::Joined(RoomTag::None))
+            })
+        })
 }
 
 pub fn add_to_fav(
diff --git a/fractal-matrix-api/src/r0.rs b/fractal-matrix-api/src/r0.rs
index 131a5e26..23c81877 100644
--- a/fractal-matrix-api/src/r0.rs
+++ b/fractal-matrix-api/src/r0.rs
@@ -1,4 +1,5 @@
 pub mod account;
+pub mod config;
 pub mod contact;
 pub mod context;
 pub mod directory;
diff --git a/fractal-matrix-api/src/r0/config.rs b/fractal-matrix-api/src/r0/config.rs
new file mode 100644
index 00000000..c1728c65
--- /dev/null
+++ b/fractal-matrix-api/src/r0/config.rs
@@ -0,0 +1,2 @@
+pub mod get_global_account_data;
+pub mod set_global_account_data;
diff --git a/fractal-matrix-api/src/r0/config/get_global_account_data.rs 
b/fractal-matrix-api/src/r0/config/get_global_account_data.rs
new file mode 100644
index 00000000..b11e327c
--- /dev/null
+++ b/fractal-matrix-api/src/r0/config/get_global_account_data.rs
@@ -0,0 +1,28 @@
+use crate::r0::AccessToken;
+use reqwest::blocking::Client;
+use reqwest::blocking::Request;
+use reqwest::Error;
+use ruma_identifiers::UserId;
+use serde::Serialize;
+use url::Url;
+
+#[derive(Clone, Debug, Serialize)]
+pub struct Parameters {
+    pub access_token: AccessToken,
+}
+
+pub fn request(
+    base: Url,
+    params: &Parameters,
+    user_id: &UserId,
+    event_type: &str, // TODO: Use EventType
+) -> Result<Request, Error> {
+    let url = base
+        .join(&format!(
+            "/_matrix/client/r0/user/{}/account_data/{}",
+            user_id, event_type,
+        ))
+        .expect("Malformed URL in get_global_account_data");
+
+    Client::new().get(url).query(params).build()
+}
diff --git a/fractal-matrix-api/src/r0/config/set_global_account_data.rs 
b/fractal-matrix-api/src/r0/config/set_global_account_data.rs
new file mode 100644
index 00000000..b82ef6b4
--- /dev/null
+++ b/fractal-matrix-api/src/r0/config/set_global_account_data.rs
@@ -0,0 +1,30 @@
+use crate::r0::AccessToken;
+use reqwest::blocking::Client;
+use reqwest::blocking::Request;
+use reqwest::Error;
+use ruma_identifiers::UserId;
+use serde::Serialize;
+use serde_json::Value as JsonValue;
+use url::Url;
+
+#[derive(Clone, Debug, Serialize)]
+pub struct Parameters {
+    pub access_token: AccessToken,
+}
+
+pub fn request(
+    base: Url,
+    params: &Parameters,
+    body: &JsonValue,
+    user_id: &UserId,
+    event_type: &str, // TODO: Use EventType
+) -> Result<Request, Error> {
+    let url = base
+        .join(&format!(
+            "/_matrix/client/r0/user/{}/account_data/{}",
+            user_id, event_type,
+        ))
+        .expect("Malformed URL in set_global_account_data");
+
+    Client::new().put(url).query(params).json(body).build()
+}


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