about summary refs log tree commit diff
path: root/src/micropub/post.rs
diff options
context:
space:
mode:
authorVika <vika@fireburn.ru>2022-03-06 17:14:10 +0300
committerVika <vika@fireburn.ru>2022-03-06 17:14:10 +0300
commit998ffd3e3ac85a38aec8fc15c7addd02fa1af9ae (patch)
tree863e7daabf52edc8448fba45fc0b3e6acdba2b0a /src/micropub/post.rs
parent11a39e85f2673029c7e317c02ae56bd8813773ad (diff)
downloadkittybox-998ffd3e3ac85a38aec8fc15c7addd02fa1af9ae.tar.zst
Restored most of the functionality (except onboarding and some queries)
Diffstat (limited to 'src/micropub/post.rs')
-rw-r--r--src/micropub/post.rs126
1 files changed, 30 insertions, 96 deletions
diff --git a/src/micropub/post.rs b/src/micropub/post.rs
index 30304e5..cf9f3d9 100644
--- a/src/micropub/post.rs
+++ b/src/micropub/post.rs
@@ -1,43 +1,18 @@
 use crate::database::Storage;
 use crate::indieauth::User;
-use crate::ApplicationState;
 use chrono::prelude::*;
 use core::iter::Iterator;
-use futures::stream;
-use futures::StreamExt;
-use http_types::Mime;
-use log::{error, info, warn};
 use newbase60::num_to_sxg;
 use std::convert::TryInto;
-use std::str::FromStr;
 use serde_json::json;
 
-static DEFAULT_CHANNEL_PATH: &str = "/feeds/main";
+pub(crate) static DEFAULT_CHANNEL_PATH: &str = "/feeds/main";
 static DEFAULT_CHANNEL_NAME: &str = "Main feed";
-static CONTACTS_CHANNEL_PATH: &str = "/feeds/vcards";
+pub(crate) static CONTACTS_CHANNEL_PATH: &str = "/feeds/vcards";
 static CONTACTS_CHANNEL_NAME: &str = "My address book";
-static FOOD_CHANNEL_PATH: &str = "/feeds/food";
+pub(crate) static FOOD_CHANNEL_PATH: &str = "/feeds/food";
 static FOOD_CHANNEL_NAME: &str = "My recipe book";
 
-macro_rules! response {
-    ($($code:expr, $json:tt)+) => {
-        $(
-            Ok(Response::builder($code).body(json!($json)).build())
-        )+
-    };
-}
-
-macro_rules! error_json {
-    ($($code:expr, $error:expr, $error_desc:expr)+) => {
-        $(
-            response!($code, {
-                "error": $error,
-                "error_description": $error_desc
-            })
-        )+
-    }
-}
-
 fn get_folder_from_type(post_type: &str) -> String {
     (match post_type {
         "h-feed" => "feeds/",
@@ -49,34 +24,31 @@ fn get_folder_from_type(post_type: &str) -> String {
     .to_string()
 }
 
+/// Reset the datetime to a proper datetime.
+/// Do not attempt to recover the information.
+/// Do not pass GO. Do not collect $200.                
+fn reset_dt(post: &mut serde_json::Value) -> DateTime<FixedOffset> {
+    let curtime: DateTime<Local> = Local::now();
+    post["properties"]["published"] = json!([curtime.to_rfc3339()]);
+    chrono::DateTime::from(curtime)
+}
+
 pub fn normalize_mf2(mut body: serde_json::Value, user: &User) -> (String, serde_json::Value) {
     // Normalize the MF2 object here.
     let me = &user.me;
-    let published: DateTime<FixedOffset>;
     let folder = get_folder_from_type(body["type"][0].as_str().unwrap());
-    if let Some(dt) = body["properties"]["published"][0].as_str() {
+    let published: DateTime<FixedOffset> = if let Some(dt) = body["properties"]["published"][0].as_str() {
         // Check if the datetime is parsable.
         match DateTime::parse_from_rfc3339(dt) {
-            Ok(dt) => {
-                published = dt;
-            }
-            Err(_) => {
-                // Reset the datetime to a proper datetime.
-                // Do not attempt to recover the information.
-                // Do not pass GO. Do not collect $200.
-                let curtime: DateTime<Local> = Local::now();
-                body["properties"]["published"] =
-                    serde_json::Value::Array(vec![serde_json::Value::String(curtime.to_rfc3339())]);
-                published = chrono::DateTime::from(curtime);
-            }
+            Ok(dt) => dt,
+            Err(_) => reset_dt(&mut body)
         }
     } else {
         // Set the datetime.
-        let curtime: DateTime<Local> = Local::now();
-        body["properties"]["published"] =
-            serde_json::Value::Array(vec![serde_json::Value::String(curtime.to_rfc3339())]);
-        published = chrono::DateTime::from(curtime);
-    }
+        // Note: this code block duplicates functionality with the above failsafe.
+        // Consider refactoring it to a helper function?
+        reset_dt(&mut body)
+    };
     match body["properties"]["uid"][0].as_str() {
         None => {
             let uid = serde_json::Value::String(
@@ -182,7 +154,7 @@ pub fn normalize_mf2(mut body: serde_json::Value, user: &User) -> (String, serde
     );
 }
 
-pub async fn new_post<S: Storage>(
+/*pub async fn new_post<S: Storage>(
     req: Request<ApplicationState<S>>,
     body: serde_json::Value,
 ) -> Result {
@@ -298,9 +270,9 @@ pub async fn new_post<S: Storage>(
         .header("Location", &uid)
         .body(json!({"status": "accepted", "location": &uid}))
         .build())
-}
+}*/
 
-async fn create_feed(
+pub(crate) async fn create_feed(
     storage: &impl Storage,
     uid: &str,
     channel: &str,
@@ -335,7 +307,7 @@ async fn create_feed(
     storage.put_post(&feed, user.me.as_str()).await
 }
 
-async fn post_process_new_post<S: Storage>(
+/*async fn post_process_new_post<S: Storage>(
     req: Request<ApplicationState<S>>,
     post: serde_json::Value,
 ) {
@@ -563,9 +535,9 @@ async fn post_process_new_post<S: Storage>(
         .buffer_unordered(3)
         .collect::<Vec<_>>()
         .await;
-}
+}*/
 
-async fn process_json<S: Storage>(
+/*async fn process_json<S: Storage>(
     req: Request<ApplicationState<S>>,
     body: serde_json::Value,
 ) -> Result {
@@ -647,31 +619,9 @@ async fn process_json<S: Storage>(
             "Try sending MF2-structured data or an object with an \"action\" and \"url\" keys."
         );
     }
-}
+}*/
 
-fn convert_form_to_mf2_json(form: Vec<(String, String)>) -> serde_json::Value {
-    let mut mf2 = json!({"type": [], "properties": {}});
-    for (k, v) in form {
-        if k == "h" {
-            mf2["type"]
-                .as_array_mut()
-                .unwrap()
-                .push(json!("h-".to_string() + &v));
-        } else if k != "access_token" {
-            let key = k.strip_suffix("[]").unwrap_or(&k);
-            match mf2["properties"][key].as_array_mut() {
-                Some(prop) => prop.push(json!(v)),
-                None => mf2["properties"][key] = json!([v]),
-            }
-        }
-    }
-    if mf2["type"].as_array().unwrap().is_empty() {
-        mf2["type"].as_array_mut().unwrap().push(json!("h-entry"));
-    }
-    mf2
-}
-
-async fn process_form<S: Storage>(
+/*async fn process_form<S: Storage>(
     req: Request<ApplicationState<S>>,
     form: Vec<(String, String)>,
 ) -> Result {
@@ -725,9 +675,9 @@ async fn process_form<S: Storage>(
         "invalid_request",
         "Try sending h=entry&content=something%20interesting"
     );
-}
+}*/
 
-pub async fn post_handler<S: Storage>(mut req: Request<ApplicationState<S>>) -> Result {
+/*pub async fn post_handler<S: Storage>(mut req: Request<ApplicationState<S>>) -> Result {
     match req.content_type() {
         Some(value) => {
             if value == Mime::from_str("application/json").unwrap() {
@@ -766,7 +716,7 @@ pub async fn post_handler<S: Storage>(mut req: Request<ApplicationState<S>>) ->
             );
         }
     }
-}
+}*/
 
 #[cfg(test)]
 mod tests {
@@ -853,22 +803,6 @@ mod tests {
         );
     }
 
-    
-    #[test]
-    fn test_form_to_mf2() {
-        use serde_urlencoded::from_str;
-
-        assert_eq!(
-            convert_form_to_mf2_json(from_str("h=entry&content=something%20interesting").unwrap()),
-            json!({
-                "type": ["h-entry"],
-                "properties": {
-                    "content": ["something interesting"]
-                }
-            })
-        )
-    }
-
     #[test]
     fn test_normalize_mf2() {
         let mf2 = json!({