1
0
Fork 0
mirror of https://github.com/Nutomic/ibis.git synced 2024-12-23 05:01:23 +00:00

User profile with displayname and bio (fixes #90)

This commit is contained in:
Felix Ableitner 2024-12-19 12:07:08 +01:00
parent 56a6ba9b8b
commit 34884e239f
18 changed files with 206 additions and 17 deletions

View file

@ -0,0 +1,2 @@
alter table person drop display_name;
alter table person drop bio;

View file

@ -0,0 +1,2 @@
alter table person add column display_name varchar(20);
alter table person add column bio varchar(1000);

View file

@ -14,9 +14,22 @@ use crate::{
common::{
utils::{extract_domain, http_protocol_str},
validation::can_edit_article,
ApiConflict, ApproveArticleForm, ArticleView, CreateArticleForm, DbArticle, DbEdit,
DbInstance, DeleteConflictForm, EditArticleForm, EditVersion, ForkArticleForm,
GetArticleForm, ListArticlesForm, LocalUserView, ProtectArticleForm, ResolveObject,
ApiConflict,
ApproveArticleForm,
ArticleView,
CreateArticleForm,
DbArticle,
DbEdit,
DbInstance,
DeleteConflictForm,
EditArticleForm,
EditVersion,
ForkArticleForm,
GetArticleForm,
ListArticlesForm,
LocalUserView,
ProtectArticleForm,
ResolveObject,
SearchArticleForm,
},
};

View file

@ -37,7 +37,7 @@ use axum::{
use axum_extra::extract::CookieJar;
use axum_macros::debug_handler;
use instance::list_remote_instances;
use user::{count_notifications, list_notifications};
use user::{count_notifications, list_notifications, update_user_profile};
pub mod article;
pub mod instance;
@ -67,6 +67,7 @@ pub fn api_routes() -> Router<()> {
.route("/account/register", post(register_user))
.route("/account/login", post(login_user))
.route("/account/logout", post(logout_user))
.route("/account/update", post(update_user_profile))
.route("/site", get(site_view))
.route_layer(middleware::from_fn(auth))
}

View file

@ -13,6 +13,7 @@ use crate::{
Notification,
RegisterUserForm,
SuccessResponse,
UpdateUserForm,
AUTH_COOKIE,
},
};
@ -143,6 +144,15 @@ pub(in crate::backend::api) async fn get_user(
)?))
}
#[debug_handler]
pub(in crate::backend::api) async fn update_user_profile(
data: Data<IbisData>,
Form(params): Form<UpdateUserForm>,
) -> MyResult<Json<SuccessResponse>> {
DbPerson::update_profile(&params, &data)?;
Ok(Json(SuccessResponse::default()))
}
#[debug_handler]
pub(crate) async fn list_notifications(
Extension(user): Extension<LocalUserView>,

View file

@ -110,6 +110,10 @@ diesel::table! {
private_key -> Nullable<Text>,
last_refreshed_at -> Timestamptz,
local -> Bool,
#[max_length = 20]
display_name -> Nullable<Varchar>,
#[max_length = 1000]
bio -> Nullable<Varchar>,
}
}

View file

@ -14,6 +14,7 @@ use crate::{
DbLocalUser,
DbPerson,
LocalUserView,
UpdateUserForm,
},
};
use activitypub_federation::{config::Data, fetch::object_id::ObjectId};
@ -49,6 +50,8 @@ pub struct DbPersonForm {
pub private_key: Option<String>,
pub last_refreshed_at: DateTime<Utc>,
pub local: bool,
pub display_name: Option<String>,
pub bio: Option<String>,
}
impl DbPerson {
@ -89,6 +92,8 @@ impl DbPerson {
private_key: Some(keypair.private_key),
last_refreshed_at: Utc::now(),
local: true,
display_name: None,
bio: None,
};
let person = insert_into(person::table)
@ -143,6 +148,17 @@ impl DbPerson {
Ok(query.get_result(conn.deref_mut())?)
}
pub fn update_profile(params: &UpdateUserForm, data: &Data<IbisData>) -> MyResult<()> {
let mut conn = data.db_pool.get()?;
diesel::update(person::table.find(params.person_id))
.set((
person::dsl::display_name.eq(&params.display_name),
person::dsl::bio.eq(&params.bio),
))
.execute(conn.deref_mut())?;
Ok(())
}
pub fn read_local_from_name(username: &str, data: &Data<IbisData>) -> MyResult<LocalUserView> {
let mut conn = data.db_pool.get()?;
let (person, local_user) = person::table
@ -191,6 +207,8 @@ impl DbPerson {
private_key: Some(keypair.private_key),
last_refreshed_at: Utc::now(),
local: true,
display_name: None,
bio: None,
};
DbPerson::create(&person_form, data)
}

View file

@ -24,6 +24,9 @@ pub struct ApubUser {
kind: PersonType,
id: ObjectId<DbPerson>,
preferred_username: String,
/// displayname
name: Option<String>,
summary: Option<String>,
inbox: Url,
public_key: PublicKey,
}
@ -48,10 +51,12 @@ impl Object for DbPerson {
async fn into_json(self, _data: &Data<Self::DataType>) -> Result<Self::Kind, Self::Error> {
Ok(ApubUser {
kind: Default::default(),
id: self.ap_id.clone(),
preferred_username: self.username.clone(),
inbox: Url::parse(&self.inbox_url)?,
public_key: self.public_key(),
id: __self.ap_id.clone(),
preferred_username: __self.username.clone(),
inbox: Url::parse(&__self.inbox_url)?,
public_key: __self.public_key(),
name: self.display_name,
summary: self.bio,
})
}
@ -73,6 +78,8 @@ impl Object for DbPerson {
private_key: None,
last_refreshed_at: Utc::now(),
local: false,
display_name: json.name,
bio: json.summary,
};
DbPerson::create(&form, data)
}

View file

@ -186,6 +186,8 @@ pub struct DbPerson {
#[serde(skip)]
pub last_refreshed_at: DateTime<Utc>,
pub local: bool,
pub display_name: Option<String>,
pub bio: Option<String>,
}
impl DbPerson {
@ -344,6 +346,13 @@ pub struct GetUserForm {
pub domain: Option<String>,
}
#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct UpdateUserForm {
pub person_id: PersonId,
pub display_name: Option<String>,
pub bio: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, SmartDefault)]
#[serde(default)]
#[serde(deny_unknown_fields)]

View file

@ -217,6 +217,14 @@ impl ApiClient {
self.get("/api/v1/user", Some(data)).await
}
pub async fn update_user_profile(
&self,
data: UpdateUserForm,
) -> Result<SuccessResponse, ServerFnError> {
log::info!("{:?}", &data);
self.post("/api/v1/account/update", Some(data)).await
}
pub async fn get_article_edits(&self, article_id: ArticleId) -> Option<Vec<EditView>> {
let data = GetEditList {
article_id: Some(article_id),
@ -344,7 +352,7 @@ impl ApiClient {
{
let json = serde_json::from_str(&text).map_err(|e| {
ServerFnError::<NoCustomError>::Deserialization(format!(
"Serde error: {e} from {text}on {url}"
"Serde error: {e} from {text} on {url}"
))
})?;
if status == StatusCode::OK {

View file

@ -19,6 +19,7 @@ use crate::{
notifications::Notifications,
register::Register,
search::Search,
user_edit_profile::UserEditProfile,
user_profile::UserProfile,
},
},
@ -122,6 +123,7 @@ pub fn App() -> impl IntoView {
<Route path=path!("/login") view=Login />
<Route path=path!("/register") view=Register />
<Route path=path!("/search") view=Search />
<IbisProtectedRoute path=path!("/edit_profile") view=UserEditProfile />
<IbisProtectedRoute path=path!("/notifications") view=Notifications />
</Routes>
</main>

View file

@ -38,7 +38,6 @@ pub fn CredentialsForm(
let val = event_target_value(&ev);
set_username.update(|v| *v = val);
}
on:change=move |ev| {
let val = event_target_value(&ev);
set_username.update(|v| *v = val);
@ -62,7 +61,6 @@ pub fn CredentialsForm(
}
}
}
on:change=move |ev| {
let val = event_target_value(&ev);
set_password.update(|p| *p = val);

View file

@ -26,7 +26,7 @@ pub fn EditorView(
<textarea
prop:value=content
placeholder="Article text..."
class="text-base text-base resize-none grow textarea textarea-primary min-h-80"
class="text-base resize-none grow textarea textarea-primary min-h-80"
on:input=move |evt| {
let val = event_target_value(&evt);
set_preview.set(render_markdown(&val));
@ -44,7 +44,7 @@ pub fn EditorView(
</div>
<div class="flex items-center mb-4 h-min">
<button
class="btn btn-secondary"
class="btn btn-secondary btn-sm"
on:click=move |_| {
cookie.1.set(Some(!show_preview.get_untracked()));
}

View file

@ -115,11 +115,14 @@ pub fn Nav() -> impl IntoView {
.with_default(|site| site.clone().my_profile.unwrap());
let profile_link = format!("/user/{}", my_profile.person.username);
view! {
<p class="self-center pb-2">
<p class="self-center">
"Logged in as " <a class="link" href=profile_link>
{my_profile.person.username}
</a>
</p>
<a class="self-center py-2 link" href="/edit_profile">
Edit Profile
</a>
<button
class="self-center w-min btn btn-outline btn-xs"
on:click=move |_| {

View file

@ -51,10 +51,14 @@ fn article_title(article: &DbArticle) -> String {
}
fn user_title(person: &DbPerson) -> String {
let name = person
.display_name
.clone()
.unwrap_or(person.username.clone());
if person.local {
person.username.clone()
name.clone()
} else {
format!("{}@{}", person.username, extract_domain(&person.ap_id))
format!("{}@{}", name, extract_domain(&person.ap_id))
}
}

View file

@ -12,6 +12,7 @@ pub(crate) mod login;
pub(crate) mod notifications;
pub(crate) mod register;
pub(crate) mod search;
pub(crate) mod user_edit_profile;
pub(crate) mod user_profile;
fn article_resource() -> Resource<ArticleView> {

View file

@ -0,0 +1,97 @@
use crate::{
common::UpdateUserForm,
frontend::{
api::CLIENT,
app::{site, DefaultResource},
},
};
use leptos::prelude::*;
#[component]
pub fn UserEditProfile() -> impl IntoView {
let (submit_error, set_submit_error) = signal(None::<String>);
let submit_action = Action::new(move |form: &UpdateUserForm| {
let form = form.clone();
async move {
let result = CLIENT.update_user_profile(form).await;
match result {
Ok(_res) => {
set_submit_error.update(|e| *e = None);
}
Err(err) => {
let msg = err.to_string();
log::warn!("Unable to update profile: {msg}");
set_submit_error.update(|e| *e = Some(msg));
}
}
}
});
// TODO: It would make sense to use a table for the labels and inputs, but for some reason
// that completely breaks reactivity.
view! {
<Suspense fallback=|| {
view! { "Loading..." }
}>
{
let my_profile = site().with_default(|site| site.clone().my_profile.unwrap());
let (display_name, set_display_name) = signal(
my_profile.person.display_name.clone().unwrap_or_default(),
);
let (bio, set_bio) = signal(my_profile.person.bio.clone().unwrap_or_default());
view! {
<h1 class="flex-auto my-6 font-serif text-4xl font-bold grow">Edit Profile</h1>
{move || {
submit_error
.get()
.map(|err| {
view! { <p class="alert alert-error">{err}</p> }
})
}}
<div class="flex flex-row mb-2">
<label class="block w-40">Displayname</label>
<input
type="text"
id="displayname"
class="w-80 input input-secondary input-bordered"
prop:value=display_name
on:change=move |ev| {
let val = event_target_value(&ev);
set_display_name.set(val);
}
/>
</div>
<div class="flex flex-row mb-2">
<label class="block w-40" for="bio">
"Bio (Markdown supported)"
</label>
<textarea
id="bio"
class="w-80 text-base textarea textarea-secondary"
prop:value=move || bio.get()
on:input:target=move |evt| {
let val = evt.target().value();
set_bio.set(val);
}
></textarea>
</div>
<button
class="btn btn-primary"
on:click=move |_| {
let form = UpdateUserForm {
person_id: my_profile.person.id,
display_name: Some(display_name.get()),
bio: Some(bio.get()),
};
submit_action.dispatch(form);
}
>
Submit
</button>
}
}
</Suspense>
}
}

View file

@ -1,6 +1,11 @@
use crate::{
common::GetUserForm,
frontend::{api::CLIENT, components::edit_list::EditList, user_title},
frontend::{
api::CLIENT,
components::edit_list::EditList,
markdown::render_markdown,
user_title,
},
};
use leptos::prelude::*;
use leptos_router::hooks::use_params_map;
@ -51,6 +56,11 @@ pub fn UserProfile() -> impl IntoView {
{user_title(&person)}
</h1>
<div
class="mb-2 max-w-full prose prose-slate"
inner_html=render_markdown(&person.bio.unwrap_or_default())
></div>
<h2 class="font-serif text-xl font-bold">Edits</h2>
<EditList edits=edits for_article=false />
}