about summary refs log tree commit diff
path: root/src/frontend
diff options
context:
space:
mode:
authorVika <vika@fireburn.ru>2025-04-09 23:31:02 +0300
committerVika <vika@fireburn.ru>2025-04-09 23:31:57 +0300
commit8826d9446e6c492db2243b9921e59ce496027bef (patch)
tree63738aa9001cb73b11cb0e974e93129bcdf1adbb /src/frontend
parent519cadfbb298f50cbf819dde757037ab56e2863e (diff)
downloadkittybox-8826d9446e6c492db2243b9921e59ce496027bef.tar.zst
cargo fmt
Change-Id: I80e81ebba3f0cdf8c094451c9fe3ee4126b8c888
Diffstat (limited to 'src/frontend')
-rw-r--r--src/frontend/mod.rs136
-rw-r--r--src/frontend/onboarding.rs26
2 files changed, 88 insertions, 74 deletions
diff --git a/src/frontend/mod.rs b/src/frontend/mod.rs
index 9ba1a69..94b8aa7 100644
--- a/src/frontend/mod.rs
+++ b/src/frontend/mod.rs
@@ -12,12 +12,10 @@ use tracing::{debug, error};
 //pub mod login;
 pub mod onboarding;
 
+pub use kittybox_frontend_renderer::assets::statics;
 use kittybox_frontend_renderer::{
-    Entry, Feed, VCard,
-    ErrorPage, Template, MainPage,
-    POSTS_PER_PAGE
+    Entry, ErrorPage, Feed, MainPage, Template, VCard, POSTS_PER_PAGE,
 };
-pub use kittybox_frontend_renderer::assets::statics;
 
 #[derive(Debug, Deserialize)]
 pub struct QueryParams {
@@ -106,7 +104,7 @@ pub fn filter_post(
         .map(|i| -> &str {
             match i {
                 serde_json::Value::String(ref author) => author.as_str(),
-                mf2 => mf2["properties"]["uid"][0].as_str().unwrap()
+                mf2 => mf2["properties"]["uid"][0].as_str().unwrap(),
             }
         })
         .map(|i| i.parse().unwrap())
@@ -116,11 +114,13 @@ pub fn filter_post(
         .unwrap_or("public");
     let audience = {
         let mut audience = author_list.clone();
-        audience.extend(post["properties"]["audience"]
-            .as_array()
-            .unwrap_or(&empty_vec)
-            .iter()
-            .map(|i| i.as_str().unwrap().parse().unwrap()));
+        audience.extend(
+            post["properties"]["audience"]
+                .as_array()
+                .unwrap_or(&empty_vec)
+                .iter()
+                .map(|i| i.as_str().unwrap().parse().unwrap()),
+        );
 
         audience
     };
@@ -134,7 +134,10 @@ pub fn filter_post(
         let location_visibility = post["properties"]["location-visibility"][0]
             .as_str()
             .unwrap_or("private");
-        tracing::debug!("Post contains location, location privacy = {}", location_visibility);
+        tracing::debug!(
+            "Post contains location, location privacy = {}",
+            location_visibility
+        );
         let mut author = post["properties"]["author"]
             .as_array()
             .unwrap_or(&empty_vec)
@@ -155,16 +158,18 @@ pub fn filter_post(
             post["properties"]["author"] = serde_json::Value::Array(
                 children
                     .into_iter()
-                    .filter_map(|post| if post.is_string() {
-                        Some(post)
-                    } else {
-                        filter_post(post, user)
+                    .filter_map(|post| {
+                        if post.is_string() {
+                            Some(post)
+                        } else {
+                            filter_post(post, user)
+                        }
                     })
-                    .collect::<Vec<serde_json::Value>>()
+                    .collect::<Vec<serde_json::Value>>(),
             );
-        },
-        serde_json::Value::Null => {},
-        other => post["properties"]["author"] = other
+        }
+        serde_json::Value::Null => {}
+        other => post["properties"]["author"] = other,
     }
 
     match post["children"].take() {
@@ -173,11 +178,11 @@ pub fn filter_post(
                 children
                     .into_iter()
                     .filter_map(|post| filter_post(post, user))
-                    .collect::<Vec<serde_json::Value>>()
+                    .collect::<Vec<serde_json::Value>>(),
             );
-        },
-        serde_json::Value::Null => {},
-        other => post["children"] = other
+        }
+        serde_json::Value::Null => {}
+        other => post["children"] = other,
     }
     Some(post)
 }
@@ -209,7 +214,7 @@ async fn get_post_from_database<S: Storage>(
                         ))
                     }
                 }
-            }
+            },
             None => Err(FrontendError::with_code(
                 StatusCode::NOT_FOUND,
                 "Post not found in the database",
@@ -240,7 +245,7 @@ pub async fn homepage<D: Storage>(
     Host(host): Host,
     Query(query): Query<QueryParams>,
     State(db): State<D>,
-    session: Option<crate::Session>
+    session: Option<crate::Session>,
 ) -> impl IntoResponse {
     // This is stupid, but there is no other way.
     let hcard_url: url::Url = format!("https://{}/", host).parse().unwrap();
@@ -252,7 +257,7 @@ pub async fn homepage<D: Storage>(
     );
     headers.insert(
         axum::http::header::X_CONTENT_TYPE_OPTIONS,
-        axum::http::HeaderValue::from_static("nosniff")
+        axum::http::HeaderValue::from_static("nosniff"),
     );
 
     let user = session.as_deref().map(|s| &s.me);
@@ -268,18 +273,16 @@ pub async fn homepage<D: Storage>(
             // btw is it more efficient to fetch these in parallel?
             let (blogname, webring, channels) = tokio::join!(
                 db.get_setting::<crate::database::settings::SiteName>(&hcard_url)
-                .map(Result::unwrap_or_default),
-
+                    .map(Result::unwrap_or_default),
                 db.get_setting::<crate::database::settings::Webring>(&hcard_url)
-                .map(Result::unwrap_or_default),
-
+                    .map(Result::unwrap_or_default),
                 db.get_channels(&hcard_url).map(|i| i.unwrap_or_default())
             );
 
             if user.is_some() {
                 headers.insert(
                     axum::http::header::CACHE_CONTROL,
-                    axum::http::HeaderValue::from_static("private")
+                    axum::http::HeaderValue::from_static("private"),
                 );
             }
             // Render the homepage
@@ -295,12 +298,13 @@ pub async fn homepage<D: Storage>(
                         feed: &hfeed,
                         card: &hcard,
                         cursor: cursor.as_deref(),
-                        webring: crate::database::settings::Setting::into_inner(webring)
+                        webring: crate::database::settings::Setting::into_inner(webring),
                     }
                     .to_string(),
                 }
                 .to_string(),
-            ).into_response()
+            )
+                .into_response()
         }
         Err(err) => {
             if err.code == StatusCode::NOT_FOUND {
@@ -310,19 +314,20 @@ pub async fn homepage<D: Storage>(
                     StatusCode::FOUND,
                     [(axum::http::header::LOCATION, "/.kittybox/onboarding")],
                     String::default(),
-                ).into_response()
+                )
+                    .into_response()
             } else {
                 error!("Error while fetching h-card and/or h-feed: {}", err);
                 // Return the error
                 let (blogname, channels) = tokio::join!(
                     db.get_setting::<crate::database::settings::SiteName>(&hcard_url)
-                    .map(Result::unwrap_or_default),
-
+                        .map(Result::unwrap_or_default),
                     db.get_channels(&hcard_url).map(|i| i.unwrap_or_default())
                 );
 
                 (
-                    err.code(), headers,
+                    err.code(),
+                    headers,
                     Template {
                         title: blogname.as_ref(),
                         blog_name: blogname.as_ref(),
@@ -335,7 +340,8 @@ pub async fn homepage<D: Storage>(
                         .to_string(),
                     }
                     .to_string(),
-                ).into_response()
+                )
+                    .into_response()
             }
         }
     }
@@ -351,17 +357,13 @@ pub async fn catchall<D: Storage>(
 ) -> impl IntoResponse {
     let user: Option<&url::Url> = session.as_deref().map(|p| &p.me);
     let host = url::Url::parse(&format!("https://{}/", host)).unwrap();
-    let path = host
-        .clone()
-        .join(uri.path())
-        .unwrap();
+    let path = host.clone().join(uri.path()).unwrap();
 
     match get_post_from_database(&db, path.as_str(), query.after, user).await {
         Ok((post, cursor)) => {
             let (blogname, channels) = tokio::join!(
                 db.get_setting::<crate::database::settings::SiteName>(&host)
-                .map(Result::unwrap_or_default),
-
+                    .map(Result::unwrap_or_default),
                 db.get_channels(&host).map(|i| i.unwrap_or_default())
             );
             let mut headers = axum::http::HeaderMap::new();
@@ -371,12 +373,12 @@ pub async fn catchall<D: Storage>(
             );
             headers.insert(
                 axum::http::header::X_CONTENT_TYPE_OPTIONS,
-                axum::http::HeaderValue::from_static("nosniff")
+                axum::http::HeaderValue::from_static("nosniff"),
             );
             if user.is_some() {
                 headers.insert(
                     axum::http::header::CACHE_CONTROL,
-                    axum::http::HeaderValue::from_static("private")
+                    axum::http::HeaderValue::from_static("private"),
                 );
             }
 
@@ -384,19 +386,20 @@ pub async fn catchall<D: Storage>(
                 let last_modified = post["properties"]["updated"]
                     .as_array()
                     .and_then(|v| v.last())
-                    .or_else(|| post["properties"]["published"]
-                        .as_array()
-                        .and_then(|v| v.last())
-                    )
+                    .or_else(|| {
+                        post["properties"]["published"]
+                            .as_array()
+                            .and_then(|v| v.last())
+                    })
                     .and_then(serde_json::Value::as_str)
-                    .and_then(|dt| chrono::DateTime::<chrono::FixedOffset>::parse_from_rfc3339(dt).ok());
+                    .and_then(|dt| {
+                        chrono::DateTime::<chrono::FixedOffset>::parse_from_rfc3339(dt).ok()
+                    });
 
                 if let Some(last_modified) = last_modified {
-                    headers.typed_insert(
-                        axum_extra::headers::LastModified::from(
-                            std::time::SystemTime::from(last_modified)
-                        )
-                    );
+                    headers.typed_insert(axum_extra::headers::LastModified::from(
+                        std::time::SystemTime::from(last_modified),
+                    ));
                 }
             }
 
@@ -410,8 +413,16 @@ pub async fn catchall<D: Storage>(
                     feeds: channels,
                     user: session.as_deref(),
                     content: match post.pointer("/type/0").and_then(|i| i.as_str()) {
-                        Some("h-entry") => Entry { post: &post, from_feed: false, }.to_string(),
-                        Some("h-feed") => Feed { feed: &post, cursor: cursor.as_deref() }.to_string(),
+                        Some("h-entry") => Entry {
+                            post: &post,
+                            from_feed: false,
+                        }
+                        .to_string(),
+                        Some("h-feed") => Feed {
+                            feed: &post,
+                            cursor: cursor.as_deref(),
+                        }
+                        .to_string(),
                         Some("h-card") => VCard { card: &post }.to_string(),
                         unknown => {
                             unimplemented!("Template for MF2-JSON type {:?}", unknown)
@@ -419,13 +430,13 @@ pub async fn catchall<D: Storage>(
                     },
                 }
                 .to_string(),
-            ).into_response()
+            )
+                .into_response()
         }
         Err(err) => {
             let (blogname, channels) = tokio::join!(
                 db.get_setting::<crate::database::settings::SiteName>(&host)
-                .map(Result::unwrap_or_default),
-
+                    .map(Result::unwrap_or_default),
                 db.get_channels(&host).map(|i| i.unwrap_or_default())
             );
             (
@@ -446,7 +457,8 @@ pub async fn catchall<D: Storage>(
                     .to_string(),
                 }
                 .to_string(),
-            ).into_response()
+            )
+                .into_response()
         }
     }
 }
diff --git a/src/frontend/onboarding.rs b/src/frontend/onboarding.rs
index bf313cf..3b53911 100644
--- a/src/frontend/onboarding.rs
+++ b/src/frontend/onboarding.rs
@@ -10,7 +10,7 @@ use axum::{
 use axum_extra::extract::Host;
 use kittybox_frontend_renderer::{ErrorPage, OnboardingPage, Template};
 use serde::Deserialize;
-use tokio::{task::JoinSet, sync::Mutex};
+use tokio::{sync::Mutex, task::JoinSet};
 use tracing::{debug, error};
 
 use super::FrontendError;
@@ -64,7 +64,8 @@ async fn onboard<D: Storage + 'static>(
         me: user_uid.clone(),
         client_id: "https://kittybox.fireburn.ru/".parse().unwrap(),
         scope: kittybox_indieauth::Scopes::new(vec![kittybox_indieauth::Scope::Create]),
-        iat: None, exp: None
+        iat: None,
+        exp: None,
     };
     tracing::debug!("User data: {:?}", user);
 
@@ -99,19 +100,21 @@ async fn onboard<D: Storage + 'static>(
             continue;
         };
         debug!("Creating feed {} with slug {}", &feed.name, &feed.slug);
-        let crate::micropub::util::NormalizedPost { id: _, post: feed } = crate::micropub::normalize_mf2(
-            serde_json::json!({
-                "type": ["h-feed"],
-                "properties": {"name": [feed.name], "mp-slug": [feed.slug]}
-            }),
-            &user,
-        );
+        let crate::micropub::util::NormalizedPost { id: _, post: feed } =
+            crate::micropub::normalize_mf2(
+                serde_json::json!({
+                    "type": ["h-feed"],
+                    "properties": {"name": [feed.name], "mp-slug": [feed.slug]}
+                }),
+                &user,
+            );
 
         db.put_post(&feed, &user.me)
             .await
             .map_err(FrontendError::from)?;
     }
-    let crate::micropub::util::NormalizedPost { id: uid, post } = crate::micropub::normalize_mf2(data.first_post, &user);
+    let crate::micropub::util::NormalizedPost { id: uid, post } =
+        crate::micropub::normalize_mf2(data.first_post, &user);
     tracing::debug!("Posting first post {}...", uid);
     crate::micropub::_post(&user, uid, post, db, http, jobset)
         .await
@@ -169,6 +172,5 @@ where
     reqwest_middleware::ClientWithMiddleware: FromRef<St>,
     St: Clone + Send + Sync + 'static,
 {
-    axum::routing::get(get)
-        .post(post::<S>)
+    axum::routing::get(get).post(post::<S>)
 }