[fractal] Backend: Use get!, post! and put! as much as possible



commit ff7e6df12672ef1b25e22ae849af0a59e472633d
Author: Alejandro Domínguez <adomu net-c com>
Date:   Sat Dec 29 21:49:59 2018 +0100

    Backend: Use get!, post! and put! as much as possible

 fractal-matrix-api/src/backend/room.rs     |  22 ++--
 fractal-matrix-api/src/backend/stickers.rs |  57 +++++----
 fractal-matrix-api/src/backend/sync.rs     | 183 +++++++++++++++--------------
 fractal-matrix-api/src/backend/user.rs     |  15 ++-
 4 files changed, 141 insertions(+), 136 deletions(-)
---
diff --git a/fractal-matrix-api/src/backend/room.rs b/fractal-matrix-api/src/backend/room.rs
index 184d3667..5c2f48fe 100644
--- a/fractal-matrix-api/src/backend/room.rs
+++ b/fractal-matrix-api/src/backend/room.rs
@@ -446,14 +446,13 @@ pub fn set_room_avatar(bk: &Backend, roomid: &str, avatar: &str) -> Result<(), E
             Ok(js) => {
                 let uri = js["content_uri"].as_str().unwrap_or_default();
                 let attrs = json!({ "url": uri });
-                match json_q("put", &roomurl, &attrs, 0) {
-                    Ok(_) => {
-                        tx.send(BKResponse::SetRoomAvatar).unwrap();
-                    }
-                    Err(err) => {
-                        tx.send(BKResponse::SetRoomAvatarError(err)).unwrap();
-                    }
-                };
+                put!(
+                    &roomurl,
+                    &attrs,
+                    |_| tx.send(BKResponse::SetRoomAvatar).unwrap(),
+                    |err| tx.send(BKResponse::SetRoomAvatarError(err)).unwrap(),
+                    0
+                );
             }
         };
     });
@@ -574,12 +573,7 @@ pub fn direct_chat(bk: &Backend, user: &Member, internal_id: String) -> Result<(
             }
 
             let attrs = json!(directs.clone());
-            match json_q("put", &direct_url, &attrs, 0) {
-                Ok(_js) => {}
-                Err(err) => {
-                    error!("{:?}", err);
-                }
-            };
+            put!(&direct_url, &attrs, |_| {}, |err| error!("{:?}", err), 0);
         },
         |err| {
             tx.send(BKResponse::NewRoomError(err, internal_id)).unwrap();
diff --git a/fractal-matrix-api/src/backend/stickers.rs b/fractal-matrix-api/src/backend/stickers.rs
index b49c0bd9..2b0a54ad 100644
--- a/fractal-matrix-api/src/backend/stickers.rs
+++ b/fractal-matrix-api/src/backend/stickers.rs
@@ -58,35 +58,44 @@ pub fn get_sticker_widget_id(bk: &Backend, then: BKCommand) -> Result<(), Error>
         "type": "m.stickerpicker",
     });
     let d = bk.data.clone();
-    let tx = bk.internal_tx.clone();
-
-    thread::spawn(move || {
-        let url = vurl(&d, "widgets/request", &[]).unwrap();
-        match json_q("post", &url, &data, globals::TIMEOUT) {
-            Ok(r) => {
-                let mut id = String::new();
-                if let Some(i) = r["id"].as_str() {
-                    id = i.to_string();
-                }
-                if let Some(i) = r["data"]["id"].as_str() {
-                    id = i.to_string();
-                }
+    let itx = bk.internal_tx.clone();
 
-                let widget_id = if id.is_empty() { None } else { Some(id) };
-                d.lock().unwrap().sticker_widget = widget_id;
+    let url = vurl(&d, "widgets/request", &[]).unwrap();
+    post!(
+        &url,
+        &data,
+        |r: JsonValue| {
+            let mut id = String::new();
+            if let Some(i) = r["id"].as_str() {
+                id = i.to_string();
             }
-            Err(Error::MatrixError(js)) => {
-                let widget_id = js["data"]["id"].as_str().map(|id| id.to_string());
-                d.lock().unwrap().sticker_widget = widget_id;
+            if let Some(i) = r["data"]["id"].as_str() {
+                id = i.to_string();
             }
-            Err(_err) => {
-                d.lock().unwrap().sticker_widget = None;
+
+            let widget_id = if id.is_empty() { None } else { Some(id) };
+            d.lock().unwrap().sticker_widget = widget_id;
+
+            if let Some(t) = itx {
+                t.send(then).unwrap();
+            }
+        },
+        |err| {
+            match err {
+                Error::MatrixError(js) => {
+                    let widget_id = js["data"]["id"].as_str().map(|id| id.to_string());
+                    d.lock().unwrap().sticker_widget = widget_id;
+                }
+                _ => {
+                    d.lock().unwrap().sticker_widget = None;
+                }
+            }
+
+            if let Some(t) = itx {
+                t.send(then).unwrap();
             }
-        };
-        if let Some(t) = tx {
-            t.send(then).unwrap();
         }
-    });
+    );
 
     Ok(())
 }
diff --git a/fractal-matrix-api/src/backend/sync.rs b/fractal-matrix-api/src/backend/sync.rs
index 7eda7150..6c3b0c22 100644
--- a/fractal-matrix-api/src/backend/sync.rs
+++ b/fractal-matrix-api/src/backend/sync.rs
@@ -11,6 +11,7 @@ use crate::util::parse_m_direct;
 use crate::util::parse_sync_events;
 use log::error;
 use serde_json::json;
+use serde_json::Value as JsonValue;
 use std::{thread, time};
 
 pub fn sync(bk: &Backend, new_since: Option<String>, initial: bool) -> Result<(), Error> {
@@ -65,106 +66,108 @@ pub fn sync(bk: &Backend, new_since: Option<String>, initial: bool) -> Result<()
 
     let attrs = json!(null);
 
-    thread::spawn(move || {
-        match json_q("get", &url, &attrs, timeout) {
-            Ok(r) => {
-                let next_batch = String::from(r["next_batch"].as_str().unwrap_or_default());
-                if let Some(since) = since {
-                    // New rooms
-                    match get_rooms_from_json(&r, &userid, &baseu) {
-                        Ok(rs) => tx.send(BKResponse::NewRooms(rs)).unwrap(),
-                        Err(err) => tx.send(BKResponse::SyncError(err)).unwrap(),
-                    };
-
-                    // Message events
-                    match get_rooms_timeline_from_json(&baseu, &r, &tk, &since) {
-                        Ok(msgs) => tx.send(BKResponse::RoomMessages(msgs)).unwrap(),
-                        Err(err) => tx.send(BKResponse::RoomMessagesError(err)).unwrap(),
-                    };
-                    // Room notifications
-                    match get_rooms_notifies_from_json(&r) {
-                        Ok(notifies) => {
-                            for (r, n, h) in notifies {
-                                tx.send(BKResponse::RoomNotifications(r.clone(), n, h))
-                                    .unwrap();
-                            }
+    get!(
+        &url,
+        &attrs,
+        |r: JsonValue| {
+            let next_batch: String = r["next_batch"].as_str().map(Into::into).unwrap_or_default();
+            if let Some(since) = since {
+                // New rooms
+                match get_rooms_from_json(&r, &userid, &baseu) {
+                    Ok(rs) => tx.send(BKResponse::NewRooms(rs)).unwrap(),
+                    Err(err) => tx.send(BKResponse::SyncError(err)).unwrap(),
+                };
+
+                // Message events
+                match get_rooms_timeline_from_json(&baseu, &r, &tk, &since) {
+                    Ok(msgs) => tx.send(BKResponse::RoomMessages(msgs)).unwrap(),
+                    Err(err) => tx.send(BKResponse::RoomMessagesError(err)).unwrap(),
+                };
+                // Room notifications
+                match get_rooms_notifies_from_json(&r) {
+                    Ok(notifies) => {
+                        for (r, n, h) in notifies {
+                            tx.send(BKResponse::RoomNotifications(r.clone(), n, h))
+                                .unwrap();
                         }
-                        Err(_) => {}
-                    };
-                    // Other events
-                    match parse_sync_events(&r) {
-                        Err(err) => tx.send(BKResponse::SyncError(err)).unwrap(),
-                        Ok(events) => {
-                            for ev in events {
-                                match ev.stype.as_ref() {
-                                    "m.room.name" => {
-                                        let name = String::from(
-                                            ev.content["name"].as_str().unwrap_or_default(),
-                                        );
-                                        tx.send(BKResponse::RoomName(ev.room.clone(), name))
-                                            .unwrap();
-                                    }
-                                    "m.room.topic" => {
-                                        let t = String::from(
-                                            ev.content["topic"].as_str().unwrap_or_default(),
-                                        );
-                                        tx.send(BKResponse::RoomTopic(ev.room.clone(), t)).unwrap();
-                                    }
-                                    "m.room.avatar" => {
-                                        tx.send(BKResponse::NewRoomAvatar(ev.room.clone()))
-                                            .unwrap();
-                                    }
-                                    "m.room.member" => {
-                                        tx.send(BKResponse::RoomMemberEvent(ev)).unwrap();
-                                    }
-                                    "m.sticker" => {
-                                        // This event is managed in the room list
-                                    }
-                                    _ => {
-                                        error!("EVENT NOT MANAGED: {:?}", ev);
-                                    }
+                    }
+                    Err(_) => {}
+                };
+                // Other events
+                match parse_sync_events(&r) {
+                    Err(err) => tx.send(BKResponse::SyncError(err)).unwrap(),
+                    Ok(events) => {
+                        for ev in events {
+                            match ev.stype.as_ref() {
+                                "m.room.name" => {
+                                    let name = ev.content["name"]
+                                        .as_str()
+                                        .map(Into::into)
+                                        .unwrap_or_default();
+                                    tx.send(BKResponse::RoomName(ev.room.clone(), name))
+                                        .unwrap();
+                                }
+                                "m.room.topic" => {
+                                    let t = ev.content["topic"]
+                                        .as_str()
+                                        .map(Into::into)
+                                        .unwrap_or_default();
+                                    tx.send(BKResponse::RoomTopic(ev.room.clone(), t)).unwrap();
+                                }
+                                "m.room.avatar" => {
+                                    tx.send(BKResponse::NewRoomAvatar(ev.room.clone())).unwrap();
+                                }
+                                "m.room.member" => {
+                                    tx.send(BKResponse::RoomMemberEvent(ev)).unwrap();
+                                }
+                                "m.sticker" => {
+                                    // This event is managed in the room list
+                                }
+                                _ => {
+                                    error!("EVENT NOT MANAGED: {:?}", ev);
                                 }
                             }
                         }
-                    };
-                } else {
-                    data.lock().unwrap().m_direct = parse_m_direct(&r);
-
-                    let rooms = match get_rooms_from_json(&r, &userid, &baseu) {
-                        Ok(rs) => rs,
-                        Err(err) => {
-                            tx.send(BKResponse::SyncError(err)).unwrap();
-                            vec![]
-                        }
-                    };
-
-                    let mut def: Option<Room> = None;
-                    let jtr = data.lock().unwrap().join_to_room.clone();
-                    if !jtr.is_empty() {
-                        if let Some(r) = rooms.iter().find(|x| x.id == jtr) {
-                            def = Some(r.clone());
-                        }
                     }
-                    tx.send(BKResponse::Rooms(rooms, def)).unwrap();
-                }
+                };
+            } else {
+                data.lock().unwrap().m_direct = parse_m_direct(&r);
+
+                let rooms = match get_rooms_from_json(&r, &userid, &baseu) {
+                    Ok(rs) => rs,
+                    Err(err) => {
+                        tx.send(BKResponse::SyncError(err)).unwrap();
+                        vec![]
+                    }
+                };
 
-                tx.send(BKResponse::Sync(next_batch.clone())).unwrap();
-                data.lock().unwrap().since = if !next_batch.is_empty() {
-                    Some(next_batch)
-                } else {
-                    None
+                let mut def: Option<Room> = None;
+                let jtr = data.lock().unwrap().join_to_room.clone();
+                if !jtr.is_empty() {
+                    if let Some(r) = rooms.iter().find(|x| x.id == jtr) {
+                        def = Some(r.clone());
+                    }
                 }
+                tx.send(BKResponse::Rooms(rooms, def)).unwrap();
             }
-            Err(err) => {
-                // we wait if there's an error to avoid 100% CPU
-                error!("Sync Error, waiting 10 seconds to respond for the next sync");
-                let ten_seconds = time::Duration::from_millis(10000);
-                thread::sleep(ten_seconds);
 
-                tx.send(BKResponse::SyncError(err)).unwrap();
+            tx.send(BKResponse::Sync(next_batch.clone())).unwrap();
+            data.lock().unwrap().since = if !next_batch.is_empty() {
+                Some(next_batch)
+            } else {
+                None
             }
-        };
-    });
+        },
+        |err| {
+            // we wait if there's an error to avoid 100% CPU
+            error!("Sync Error, waiting 10 seconds to respond for the next sync");
+            let ten_seconds = time::Duration::from_millis(10000);
+            thread::sleep(ten_seconds);
+
+            tx.send(BKResponse::SyncError(err)).unwrap();
+        },
+        timeout
+    );
 
     Ok(())
 }
diff --git a/fractal-matrix-api/src/backend/user.rs b/fractal-matrix-api/src/backend/user.rs
index 6905dba6..7ecdf5bd 100644
--- a/fractal-matrix-api/src/backend/user.rs
+++ b/fractal-matrix-api/src/backend/user.rs
@@ -478,14 +478,13 @@ pub fn set_user_avatar(bk: &Backend, avatar: String) -> Result<(), Error> {
             Ok(js) => {
                 let uri = js["content_uri"].as_str().unwrap_or_default();
                 let attrs = json!({ "avatar_url": uri });
-                match json_q("put", &url, &attrs, 0) {
-                    Ok(_) => {
-                        tx.send(BKResponse::SetUserAvatar(avatar)).unwrap();
-                    }
-                    Err(err) => {
-                        tx.send(BKResponse::SetUserAvatarError(err)).unwrap();
-                    }
-                };
+                put!(
+                    &url,
+                    &attrs,
+                    |_| tx.send(BKResponse::SetUserAvatar(avatar)).unwrap(),
+                    |err| tx.send(BKResponse::SetUserAvatarError(err)).unwrap(),
+                    0
+                );
             }
         };
     });


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