about summary refs log tree commit diff
path: root/kittybox-rs/src/frontend/onboarding.rs
blob: b498aed5c4c52ed333caa8fa1721d4e3d33d1f28 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
use crate::database::{Settings, Storage};
use axum::{
    extract::{Extension, Host},
    http::StatusCode,
    response::{Html, IntoResponse},
    Json,
};
use kittybox_templates::{ErrorPage, OnboardingPage, Template};
use serde::Deserialize;
use tracing::{debug, error};

use super::FrontendError;

pub async fn get() -> Html<String> {
    Html(
        Template {
            title: "Kittybox - Onboarding",
            blog_name: "Kittybox",
            feeds: vec![],
            user: None,
            content: OnboardingPage {}.to_string(),
        }
        .to_string(),
    )
}

#[derive(Deserialize, Debug)]
struct OnboardingFeed {
    slug: String,
    name: String,
}

#[derive(Deserialize, Debug)]
pub struct OnboardingData {
    user: serde_json::Value,
    first_post: serde_json::Value,
    #[serde(default = "OnboardingData::default_blog_name")]
    blog_name: String,
    feeds: Vec<OnboardingFeed>,
}

impl OnboardingData {
    fn default_blog_name() -> String {
        "Kitty Box!".to_owned()
    }
}

#[tracing::instrument(skip(db, http))]
async fn onboard<D: Storage + 'static>(
    db: D,
    user_uid: url::Url,
    data: OnboardingData,
    http: reqwest::Client,
) -> Result<(), FrontendError> {
    // Create a user to pass to the backend
    // At this point the site belongs to nobody, so it is safe to do
    let user =
        crate::tokenauth::User::new(user_uid.as_str(), "https://kittybox.fireburn.ru/", "create");

    if data.user["type"][0] != "h-card" || data.first_post["type"][0] != "h-entry" {
        return Err(FrontendError::with_code(
            StatusCode::BAD_REQUEST,
            "user and first_post should be an h-card and an h-entry",
        ));
    }

    db.set_setting(Settings::SiteName, user.me.as_str(), &data.blog_name)
        .await
        .map_err(FrontendError::from)?;

    let (_, hcard) = {
        let mut hcard = data.user;
        hcard["properties"]["uid"] = serde_json::json!([&user_uid]);
        crate::micropub::normalize_mf2(hcard, &user)
    };
    db.put_post(&hcard, user_uid.as_str())
        .await
        .map_err(FrontendError::from)?;

    debug!("Creating feeds...");
    for feed in data.feeds {
        if feed.name.is_empty() || feed.slug.is_empty() {
            continue;
        };
        debug!("Creating feed {} with slug {}", &feed.name, &feed.slug);
        let (_, 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_uid.as_str())
            .await
            .map_err(FrontendError::from)?;
    }
    let (uid, post) = crate::micropub::normalize_mf2(data.first_post, &user);
    crate::micropub::_post(user, uid, post, db, http)
        .await
        .map_err(|e| FrontendError {
            msg: "Error while posting the first post".to_string(),
            source: Some(Box::new(e)),
            code: StatusCode::INTERNAL_SERVER_ERROR,
        })?;

    Ok(())
}

pub async fn post<D: Storage + 'static>(
    Extension(db): Extension<D>,
    Host(host): Host,
    Json(data): Json<OnboardingData>,
    Extension(http): Extension<reqwest::Client>,
) -> axum::response::Response {
    let user_uid = format!("https://{}/", host.as_str());

    if db.post_exists(&user_uid).await.unwrap() {
        IntoResponse::into_response((StatusCode::FOUND, [("Location", "/")]))
    } else {
        match onboard(db, user_uid.parse().unwrap(), data, http).await {
            Ok(()) => IntoResponse::into_response((StatusCode::FOUND, [("Location", "/")])),
            Err(err) => {
                error!("Onboarding error: {}", err);
                IntoResponse::into_response((
                    err.code(),
                    Html(
                        Template {
                            title: "Kittybox - Onboarding",
                            blog_name: "Kittybox",
                            feeds: vec![],
                            user: None,
                            content: ErrorPage {
                                code: err.code(),
                                msg: Some(err.msg().to_string()),
                            }
                            .to_string(),
                        }
                        .to_string(),
                    ),
                ))
            }
        }
    }
}

pub fn router<S: Storage + 'static>(database: S, http: reqwest::Client) -> axum::routing::MethodRouter {
    axum::routing::get(get)
        .post(post::<S>)
        .layer(axum::Extension(database))
        .layer(axum::Extension(http))
}