add: profiles ui, communities ui, posts ui

This commit is contained in:
trisua 2025-03-29 00:26:56 -04:00
parent 00abbc8fa2
commit eecf357325
36 changed files with 1460 additions and 147 deletions

View file

@ -29,6 +29,7 @@ pub const ME_JS: &str = include_str!("./public/js/me.js");
// html
pub const ROOT: &str = include_str!("./public/html/root.html");
pub const MACROS: &str = include_str!("./public/html/macros.html");
pub const COMPONENTS: &str = include_str!("./public/html/components.html");
pub const MISC_INDEX: &str = include_str!("./public/html/misc/index.html");
pub const MISC_ERROR: &str = include_str!("./public/html/misc/error.html");
@ -41,6 +42,9 @@ pub const PROFILE_BASE: &str = include_str!("./public/html/profile/base.html");
pub const PROFILE_POSTS: &str = include_str!("./public/html/profile/posts.html");
pub const COMMUNITIES_LIST: &str = include_str!("./public/html/communities/list.html");
pub const COMMUNITIES_BASE: &str = include_str!("./public/html/communities/base.html");
pub const COMMUNITIES_FEED: &str = include_str!("./public/html/communities/feed.html");
pub const COMMUNITIES_POST: &str = include_str!("./public/html/communities/post.html");
// langs
pub const LANG_EN_US: &str = include_str!("./langs/en-US.toml");
@ -136,6 +140,7 @@ pub(crate) async fn write_assets(config: &Config) -> PathBufD {
write_template!(html_path->"root.html"(crate::assets::ROOT) --config=config);
write_template!(html_path->"macros.html"(crate::assets::MACROS) --config=config);
write_template!(html_path->"components.html"(crate::assets::COMPONENTS) --config=config);
write_template!(html_path->"misc/index.html"(crate::assets::MISC_INDEX) -d "misc" --config=config);
write_template!(html_path->"misc/error.html"(crate::assets::MISC_ERROR) --config=config);
@ -148,6 +153,9 @@ pub(crate) async fn write_assets(config: &Config) -> PathBufD {
write_template!(html_path->"profile/posts.html"(crate::assets::PROFILE_POSTS) --config=config);
write_template!(html_path->"communities/list.html"(crate::assets::COMMUNITIES_LIST) -d "communities" --config=config);
write_template!(html_path->"communities/base.html"(crate::assets::COMMUNITIES_BASE) --config=config);
write_template!(html_path->"communities/feed.html"(crate::assets::COMMUNITIES_FEED) --config=config);
write_template!(html_path->"communities/post.html"(crate::assets::COMMUNITIES_POST) --config=config);
html_path
}
@ -161,9 +169,15 @@ pub(crate) async fn init_dirs(config: &Config) {
create_dir_if_not_exists!(
&PathBufD::current().extend(&[config.dirs.media.as_str(), "avatars"])
);
create_dir_if_not_exists!(
&PathBufD::current().extend(&[config.dirs.media.as_str(), "community_avatars"])
);
create_dir_if_not_exists!(
&PathBufD::current().extend(&[config.dirs.media.as_str(), "banners"])
);
create_dir_if_not_exists!(
&PathBufD::current().extend(&[config.dirs.media.as_str(), "community_banners"])
);
write_if_track!(images_path->"default-avatar.svg"(DEFAULT_AVATAR) --config=config);
write_if_track!(images_path->"default-banner.svg"(DEFAULT_BANNER) --config=config);
@ -191,6 +205,15 @@ pub(crate) async fn initial_context(
let mut ctx = Context::new();
ctx.insert("config", &config);
ctx.insert("user", &user);
if let Some(ua) = user {
ctx.insert("is_helper", &ua.permissions.check_helper());
ctx.insert("is_manager", &ua.permissions.check_manager());
} else {
ctx.insert("is_helper", &false);
ctx.insert("is_manager", &false);
}
ctx.insert("lang", &lang.data);
ctx.insert("random_cache_breaker", &CACHE_BREAKER.clone());
ctx

View file

@ -4,6 +4,7 @@ version = "1.0.0"
[data]
"general:link.home" = "Home"
"general:link.communities" = "Communities"
"general:action.delete" = "Delete"
"dialog:action.okay" = "Ok"
"dialog:action.continue" = "Continue"
@ -20,8 +21,18 @@ version = "1.0.0"
"auth:link.settings" = "Settings"
"auth:label.followers" = "Followers"
"auth:label.following" = "Following"
"auth:label.joined_journals" = "Joined Journals"
"auth:label.joined_communities" = "Joined communities"
"auth:label.recent_posts" = "Recent posts"
"communities:action.create" = "Create"
"communities:label.create_new" = "Create new community"
"communities:label.name" = "Name"
"communities:action.join" = "Join"
"communities:action.leave" = "Leave"
"communities:action.configure" = "Configure"
"communities:label.create_post" = "Create post"
"communities:label.content" = "Content"
"communities:label.posts" = "Posts"
"communities:label.create_reply" = "Create reply"
"communities:label.replies" = "Replies"
"communities:action.continue_thread" = "Continue thread"

View file

@ -78,11 +78,7 @@ body {
overflow-x: hidden;
}
main,
article,
nav,
header,
footer {
main {
width: 80ch;
margin: 0 auto;
padding: 0.75rem 1rem;
@ -422,11 +418,16 @@ select {
transition: background 0.15s;
resize: vertical;
width: 100%;
font-family: inherit;
/* personality */
background: transparent;
color: inherit;
}
textarea {
min-height: 5rem;
}
input:focus,
textarea:focus,
select:focus {
@ -1062,6 +1063,10 @@ details.accordion .inner {
}
@media screen and (max-width: 900px) {
.flex-collapse {
flex-direction: column !important;
}
.sm\:static {
position: static !important;
}

View file

@ -0,0 +1,87 @@
{% import "macros.html" as macros %} {% import "components.html" as components
%} {% extends "root.html" %} {% block head %}
<title>{{ community.context.display_name }} - {{ config.name }}</title>
{% endblock %} {% block body %} {{ macros::nav() }}
<article>
<div class="content_container">
<div class="w-full flex gap-4 flex-collapse">
<div
class="lhs flex flex-col gap-2 sm:w-full"
style="min-width: 20rem"
>
<div class="card-nest w-full">
<div class="card flex gap-2" id="community_avatar_and_name">
{{
components::community_avatar(id=community.id,size="72px")
}}
<div class="flex flex-col">
<!-- prettier-ignore -->
<h3 id="title" class="title">
{% if community.context.display_name %}
{{ community.context.display_name }}
{% else %}
{{ community.username }}
{% endif %}
</h3>
<span class="fade">{{ community.title }}</span>
</div>
</div>
{% if user %}
<div class="card flex" id="join_or_leave">
{% if not is_owner %} {% if not is_member %}
<button class="primary">
{{ icon "circle-plus" }}
<span>{{ text "communities:action.join" }}</span>
</button>
{% else %}
<button class="camo red">
{{ icon "circle-minus" }}
<span>{{ text "communities:action.leave" }}</span>
</button>
{% endif %} {% else %}
<a
href="/community/{{ community.title }}/manage"
class="button primary"
>
{{ icon "settings" }}
<span
>{{ text "communities:action.configure" }}</span
>
</a>
{% endif %}
</div>
{% endif %}
</div>
<div class="card-nest flex flex-col">
<div id="bio" class="card small">
{{ community.context.description }}
</div>
<div class="card flex flex-col gap-2">
<div class="w-full flex justify-between items-center">
<span class="notification chip">ID</span>
<button
title="Copy"
onclick="trigger('atto::copy_text', [{{ community.id }}])"
class="camo small"
>
{{ icon "copy" }}
</button>
</div>
<div class="w-full flex justify-between items-center">
<span class="notification chip">Created</span>
<span class="date">{{ community.created }}</span>
</div>
</div>
</div>
</div>
<div class="rhs w-full">{% block content %}{% endblock %}</div>
</div>
</div>
</article>
{% endblock %}

View file

@ -0,0 +1,79 @@
{% import "macros.html" as macros %} {% import "components.html" as components
%} {% extends "communities/base.html" %} {% block content %}
<div class="flex flex-col gap-4 w-full">
{% if user %}
<div class="card-nest">
<div class="card small">
<b>{{ text "communities:label.create_post" }}</b>
</div>
<form
class="card flex flex-col gap-2"
onsubmit="create_post_from_form(event)"
>
<div class="flex flex-col gap-1">
<label for="content"
>{{ text "communities:label.content" }}</label
>
<textarea
type="text"
name="content"
id="content"
placeholder="content"
required
minlength="2"
maxlength="4096"
></textarea>
</div>
<button class="primary">
{{ text "communities:action.create" }}
</button>
</form>
</div>
{% endif %}
<div class="card-nest">
<div class="card small flex gap-2 items-center">
{{ icon "newspaper" }}
<span>{{ text "communities:label.posts" }}</span>
</div>
<div class="card flex flex-col gap-4">
<!-- prettier-ignore -->
{% for post in feed %}
{{ components::post(post=post[0], owner=post[1], secondary=true, show_community=false) }}
{% endfor %}
</div>
</div>
</div>
<script>
function create_post_from_form(e) {
e.preventDefault();
fetch("/api/v1/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
content: e.target.content.value,
community: "{{ community.id }}",
}),
})
.then((res) => res.json())
.then((res) => {
trigger("atto::toast", [
res.ok ? "success" : "error",
res.message,
]);
if (res.ok) {
setTimeout(() => {
window.location.href = `/post/${res.payload}`;
}, 100);
}
});
}
</script>
{% endblock %}

View file

@ -1,13 +1,18 @@
{% import "macros.html" as macros %} {% extends "root.html" %} {% block head %}
{% import "macros.html" as macros %} {% import "components.html" as components
%} {% extends "root.html" %} {% block head %}
<title>My communities - {{ config.name }}</title>
{% endblock %} {% block body %} {{ macros::nav(selected="communities") }}
<main class="flex flex-col gap-2">
{% if user %}
<div class="card-nest">
<div class="card">
<div class="card small">
<b>{{ text "communities:label.create_new" }}</b>
</div>
<form class="card flex flex-col gap-2">
<form
class="card flex flex-col gap-2"
onsubmit="create_community_from_form(event)"
>
<div class="flex flex-col gap-1">
<label for="">{{ text "communities:label.name" }}</label>
<input
@ -26,5 +31,35 @@
</button>
</form>
</div>
{% endif %} {% for item in list %} {{
components::community_listing_card(community=item) }} {% endfor %}
</main>
<script>
function create_community_from_form(e) {
e.preventDefault();
fetch("/api/v1/communities", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: e.target.title.value,
}),
})
.then((res) => res.json())
.then((res) => {
trigger("atto::toast", [
res.ok ? "success" : "error",
res.message,
]);
if (res.ok) {
setTimeout(() => {
window.location.href = `/community/${res.payload}`;
}, 100);
}
});
}
</script>
{% endblock %}

View file

@ -0,0 +1,86 @@
{% import "macros.html" as macros %} {% import "components.html" as components
%} {% extends "root.html" %} {% block head %}
<title>Post - {{ config.name }}</title>
{% endblock %} {% block body %} {{ macros::nav() }}
<main class="flex flex-col gap-2">
{% if post.replying_to %}
<a href="/post/{{ post.replying_to }}" class="button">
{{ icon "arrow-up" }}
<span>{{ text "communities:action.continue_thread" }}</span>
</a>
{% endif %} {{ components::post(post=post, owner=owner, community=community,
show_community=true) }} {% if user %}
<div class="card-nest">
<div class="card small">
<b>{{ text "communities:label.create_reply" }}</b>
</div>
<form
class="card flex flex-col gap-2"
onsubmit="create_reply_from_form(event)"
>
<div class="flex flex-col gap-1">
<label for="content"
>{{ text "communities:label.content" }}</label
>
<textarea
type="text"
name="content"
id="content"
placeholder="content"
required
minlength="2"
maxlength="4096"
></textarea>
</div>
<button class="primary">
{{ text "communities:action.create" }}
</button>
</form>
</div>
{% endif %}
<div class="card-nest w-full">
<div class="card small flex items-center gap-2">
{{ icon "newspaper" }}
<span>{{ text "communities:label.replies" }}</span>
</div>
<div class="card flex flex-col gap-4">
{% for post in replies %} {{ components::post(post=post[0],
owner=post[1], secondary=true, show_community=false) }} {% endfor %}
</div>
</div>
</main>
<script>
function create_reply_from_form(e) {
e.preventDefault();
fetch("/api/v1/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
content: e.target.content.value,
community: "{{ community.id }}",
replying_to: "{{ post.id }}",
}),
})
.then((res) => res.json())
.then((res) => {
trigger("atto::toast", [
res.ok ? "success" : "error",
res.message,
]);
if (res.ok) {
setTimeout(() => {
window.location.href = `/post/${res.payload}`;
}, 100);
}
});
}
</script>
{% endblock %}

View file

@ -0,0 +1,125 @@
{% macro avatar(username, size="24px", selector_type="username") -%}
<img
title="{{ username }}'s avatar"
src="/api/v1/auth/profile/{{ username }}/avatar?selector_type={{ selector_type }}"
alt="@{{ username }}"
class="avatar shadow"
style="--size: {{ size }}"
/>
{%- endmacro %} {% macro community_avatar(id, community=false, size="24px") -%}
{% if community %}
<img
src="/api/v1/communities/{{ id }}/avatar"
alt="{{ community.title }}"
class="avatar shadow"
style="--size: {{ size }}"
/>
{% else %}
<img
src="/api/v1/communities/{{ id }}/avatar"
alt="{{ id }}"
class="avatar shadow"
style="--size: {{ size }}"
/>
{% endif %} {%- endmacro %} {% macro community_listing_card(community) -%}
<a
class="card w-full flex items-center gap-4"
href="/community/{{ community.title }}"
>
{{ components::community_avatar(id=community.id, community=community,
size="48px") }}
<div class="flex flex-col gap-1">
<h3>{{ community.context.display_name }}</h3>
<span class="fade"><b>{{ community.member_count }}</b> members</span>
</div>
</a>
{%- endmacro %} {% macro username(user) -%}
<div style="display: contents">
{% if user.settings.display_name %} {{ user.settings.display_name }} {% else
%} {{ user.username }} {% endif %}
</div>
{%- endmacro %} {% macro post(post, owner, secondary=false, community=false,
show_community=true) -%}
<div class="card flex flex-col gap-2 {% if secondary %}secondary{% endif %}">
<div class="w-full flex gap-2">
<a href="/user/{{ owner.username }}">
{{ components::avatar(username=post.owner, size="52px",
selector_type="id") }}
</a>
<div class="flex flex-col w-full gap-1">
<div class="flex flex-wrap gap-2 items-center">
<a href="/user/{{ owner.username }}"
>{{ components::username(user=owner) }}</a
>
<span class="fade date">{{ post.created }}</span>
{% if show_community %}
<a href="/api/v1/communities/find/{{ post.community }}">
<!-- prettier-ignore -->
{% if community %}
{{ components::community_avatar(id=post.community,
community=community) }}
{% else %}
{{ components::community_avatar(id=post.community) }}
{% endif %}
</a>
{% endif %}
</div>
<span id="post-content:{{ post.id }}">{{ post.content }}</span>
</div>
</div>
<div class="flex justify-between items-center gap-2 w-full">
<div class="flex gap-1 reactions_box">
{% if user %}
<button title="Like" class="primary small">
{{ icon "heart" }}
</button>
<button title="Dislike" class="secondary small">
{{ icon "heart-crack" }}
</button>
{% endif %}
</div>
<div class="flex gap-1 buttons_box">
<a href="/post/{{ post.id }}" class="button camo small">
{{ icon "message-circle" }}
<span>{{ post.comment_count }}</span>
</a>
<a
href="/post/{{ post.id }}"
class="button camo small"
target="_blank"
>
{{ icon "external-link" }}
</a>
{% if user %} {% if (user.id == post.owner) or is_helper %}
<div class="dropdown">
<button
class="camo small"
onclick="trigger('atto::hooks::dropdown', [event])"
exclude="dropdown"
>
{{ icon "ellipsis" }}
</button>
<div class="inner">
<button
class="red"
onclick="trigger('me::remove_post', ['{{ post.id }}'])"
>
{{ icon "trash" }}
<span>{{ text "general:action.delete" }}</span>
</button>
</div>
</div>
{% endif %} {% endif %}
</div>
</div>
</div>
{%- endmacro %}

View file

@ -1,4 +1,5 @@
{% macro nav(selected="", show_lhs=true) -%}
{% import "components.html" as components %} {% macro nav(selected="",
show_lhs=true) -%}
<nav>
<div class="content_container">
<div class="flex nav_side">
@ -46,7 +47,7 @@
exclude="dropdown"
style="gap: 0.25rem !important"
>
{{ macros::avatar(username=user.username, size="24px") }}
{{ components::avatar(username=user.username, size="24px") }}
{{ icon "chevron-down" c(dropdown-arrow) }}
</button>
@ -94,12 +95,4 @@
</div>
</div>
</nav>
{%- endmacro %} {% macro avatar(username, size="24px") -%}
<img
title="{{ username }}'s avatar"
src="/api/v1/auth/profile/{{ username }}/avatar"
alt="@{{ username }}"
class="avatar shadow"
style="--size: {{ size }}"
/>
{%- endmacro %}

View file

@ -10,7 +10,8 @@
>
<div class="card-nest w-full">
<div class="card flex gap-2" id="user_avatar_and_name">
{{ macros::avatar(username=profile.username,size="72px")
{{
components::avatar(username=profile.username,size="72px")
}}
<div class="flex flex-col">
<!-- prettier-ignore -->
@ -77,14 +78,21 @@
<div class="card-nest">
<div class="card small flex gap-2 items-center">
{{ icon "users-round" }}
<span>{{ text "auth:label.joined_journals" }}</span>
<span>{{ text "auth:label.joined_communities" }}</span>
</div>
<div class="card flex flex-wrap gap-2"></div>
<div class="card flex flex-wrap gap-2">
{% for community in communities %}
<a href="/community/{{ community.title }}">
{{ components::community_avatar(id=community.id,
community=community, size="48px") }}
</a>
{% endfor %}
</div>
</div>
</div>
<div class="rhs sm:w-full">{% block content %}{% endblock %}</div>
<div class="rhs w-full">{% block content %}{% endblock %}</div>
</div>
</div>
</article>

View file

@ -1,2 +1,16 @@
{% import "macros.html" as macros %} {% extends "profile/base.html" %} {% block
content %}<span></span>{% endblock %}
content %}
<div class="card-nest">
<div class="card small flex gap-2 items-center">
{{ icon "clock" }}
<span>{{ text "auth:label.recent_posts" }}</span>
</div>
<div class="card flex flex-col gap-4">
<!-- prettier-ignore -->
{% for post in posts %}
{{ components::post(post=post[0], owner=post[1], secondary=true, community=post[2], show_community=true) }}
{% endfor %}
</div>
</div>
{% endblock %}

View file

@ -27,4 +27,25 @@
}
});
});
self.define("remove_post", async (_, id) => {
if (
!(await trigger("atto::confirm", [
"Are you sure you want to do this?",
]))
) {
return;
}
fetch(`/api/v1/posts/${id}`, {
method: "DELETE",
})
.then((res) => res.json())
.then((res) => {
trigger("atto::toast", [
res.ok ? "success" : "error",
res.message,
]);
});
});
})();

View file

@ -1,6 +1,12 @@
use axum::{Extension, Json, body::Body, extract::Path, response::IntoResponse};
use axum::{
Extension, Json,
body::Body,
extract::{Path, Query},
response::IntoResponse,
};
use axum_extra::extract::CookieJar;
use pathbufd::{PathBufD, pathd};
use serde::Deserialize;
use std::{
fs::{File, exists},
io::Read,
@ -23,15 +29,36 @@ pub fn read_image(path: PathBufD) -> Vec<u8> {
bytes
}
#[derive(Deserialize, PartialEq, Eq)]
pub enum AvatarSelectorType {
#[serde(alias = "username")]
Username,
#[serde(alias = "id")]
Id,
}
#[derive(Deserialize)]
pub struct AvatarSelectorQuery {
pub selector_type: AvatarSelectorType,
}
/// Get a profile's avatar image
/// `/api/v1/auth/profile/{id}/avatar`
pub async fn avatar_request(
Path(username): Path<String>,
Path(selector): Path<String>,
Extension(data): Extension<State>,
Query(req): Query<AvatarSelectorQuery>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match data.get_user_by_username(&username).await {
let user = match {
if req.selector_type == AvatarSelectorType::Id {
data.get_user_by_id(selector.parse::<usize>().unwrap())
.await
} else {
data.get_user_by_username(&selector).await
}
} {
Ok(ua) => ua,
Err(_) => {
return (
@ -88,7 +115,7 @@ pub async fn banner_request(
};
let path =
PathBufD::current().extend(&["avatars", &data.0.dirs.media, &format!("{}.avif", &user.id)]);
PathBufD::current().extend(&["banners", &data.0.dirs.media, &format!("{}.avif", &user.id)]);
if !exists(&path).unwrap() {
return (
@ -107,7 +134,7 @@ pub async fn banner_request(
)
}
static MAXIUMUM_FILE_SIZE: usize = 8388608;
pub static MAXIUMUM_FILE_SIZE: usize = 8388608;
/// Upload avatar
pub async fn upload_avatar_request(

View file

@ -3,13 +3,33 @@ use crate::{
model::{ApiReturn, Error},
routes::api::v1::UpdateUserIsVerified,
};
use axum::{Extension, Json, extract::Path, response::IntoResponse};
use axum::{
Extension, Json,
extract::Path,
response::{IntoResponse, Redirect},
};
use axum_extra::extract::CookieJar;
use tetratto_core::model::{
auth::{Token, UserSettings},
permissions::FinePermission,
};
pub async fn redirect_from_id(
Extension(data): Extension<State>,
Path(id): Path<String>,
) -> impl IntoResponse {
match (&(data.read().await).0)
.get_user_by_id(match id.parse::<usize>() {
Ok(id) => id,
Err(_) => return Redirect::to("/"),
})
.await
{
Ok(u) => Redirect::to(&format!("/user/{}", u.username)),
Err(_) => Redirect::to("/"),
}
}
/// Update the settings of the given user.
pub async fn update_profile_settings_request(
jar: CookieJar,

View file

@ -1,15 +1,35 @@
use axum::{Extension, Json, extract::Path, response::IntoResponse};
use axum::{
Extension, Json,
extract::Path,
response::{IntoResponse, Redirect},
};
use axum_extra::extract::CookieJar;
use tetratto_core::model::{ApiReturn, Error, communities::Community};
use crate::{
State, get_user_from_token,
routes::api::v1::{
CreateCommunity, UpdateCommunityContext, UpdateJournalReadAccess, UpdateJournalTitle,
UpdateJournalWriteAccess,
CreateCommunity, UpdateCommunityContext, UpdateCommunityReadAccess, UpdateCommunityTitle,
UpdateCommunityWriteAccess,
},
};
pub async fn redirect_from_id(
Extension(data): Extension<State>,
Path(id): Path<String>,
) -> impl IntoResponse {
match (&(data.read().await).0)
.get_community_by_id(match id.parse::<usize>() {
Ok(id) => id,
Err(_) => return Redirect::to("/"),
})
.await
{
Ok(c) => Redirect::to(&format!("/community/{}", c.title)),
Err(_) => Redirect::to("/"),
}
}
pub async fn create_request(
jar: CookieJar,
Extension(data): Extension<State>,
@ -25,10 +45,10 @@ pub async fn create_request(
.create_community(Community::new(req.title, user.id))
.await
{
Ok(_) => Json(ApiReturn {
Ok(id) => Json(ApiReturn {
ok: true,
message: "Community created".to_string(),
payload: (),
payload: Some(id.to_string()),
}),
Err(e) => return Json(e.into()),
}
@ -59,7 +79,7 @@ pub async fn update_title_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
Json(req): Json<UpdateJournalTitle>,
Json(req): Json<UpdateCommunityTitle>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data) {
@ -103,7 +123,7 @@ pub async fn update_read_access_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
Json(req): Json<UpdateJournalReadAccess>,
Json(req): Json<UpdateCommunityReadAccess>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data) {
@ -128,7 +148,7 @@ pub async fn update_write_access_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
Json(req): Json<UpdateJournalWriteAccess>,
Json(req): Json<UpdateCommunityWriteAccess>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data) {

View file

@ -0,0 +1,214 @@
use axum::{Extension, Json, body::Body, extract::Path, response::IntoResponse};
use axum_extra::extract::CookieJar;
use pathbufd::{PathBufD, pathd};
use std::fs::exists;
use tetratto_core::model::{ApiReturn, Error, permissions::FinePermission};
use crate::{
State,
avif::{Image, save_avif_buffer},
get_user_from_token,
routes::api::v1::auth::images::{MAXIUMUM_FILE_SIZE, read_image},
};
/// Get a community's avatar image
/// `/api/v1/communities/{id}/avatar`
pub async fn avatar_request(
Path(id): Path<usize>,
Extension(data): Extension<State>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let community = match data.get_community_by_id(id).await {
Ok(ua) => ua,
Err(_) => {
return (
[("Content-Type", "image/svg+xml")],
Body::from(read_image(PathBufD::current().extend(&[
data.0.dirs.media.as_str(),
"images",
"default-avatar.svg",
]))),
);
}
};
let path = PathBufD::current().extend(&[
"community_avatars",
&data.0.dirs.media,
&format!("{}.avif", &community.id),
]);
if !exists(&path).unwrap() {
return (
[("Content-Type", "image/svg+xml")],
Body::from(read_image(PathBufD::current().extend(&[
data.0.dirs.media.as_str(),
"images",
"default-avatar.svg",
]))),
);
}
(
[("Content-Type", "image/avif")],
Body::from(read_image(path)),
)
}
/// Get a profile's banner image
/// `/api/v1/auth/profile/{id}/banner`
pub async fn banner_request(
Path(id): Path<usize>,
Extension(data): Extension<State>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let community = match data.get_community_by_id(id).await {
Ok(ua) => ua,
Err(_) => {
return (
[("Content-Type", "image/svg+xml")],
Body::from(read_image(PathBufD::current().extend(&[
data.0.dirs.media.as_str(),
"images",
"default-banner.svg",
]))),
);
}
};
let path = PathBufD::current().extend(&[
"community_banners",
&data.0.dirs.media,
&format!("{}.avif", &community.id),
]);
if !exists(&path).unwrap() {
return (
[("Content-Type", "image/svg+xml")],
Body::from(read_image(PathBufD::current().extend(&[
data.0.dirs.media.as_str(),
"images",
"default-banner.svg",
]))),
);
}
(
[("Content-Type", "image/avif")],
Body::from(read_image(path)),
)
}
/// Upload avatar
pub async fn upload_avatar_request(
jar: CookieJar,
Path(id): Path<usize>,
Extension(data): Extension<State>,
img: Image,
) -> impl IntoResponse {
// get user from token
let data = &(data.read().await).0;
let auth_user = match get_user_from_token!(jar, data) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
let community = match data.get_community_by_id(id).await {
Ok(c) => c,
Err(e) => return Json(e.into()),
};
if auth_user.id != community.owner {
if !auth_user
.permissions
.check(FinePermission::MANAGE_COMMUNITIES)
{
return Json(Error::NotAllowed.into());
}
}
let path = pathd!(
"{}/community_avatars/{}.avif",
data.0.dirs.media,
&auth_user.id
);
// check file size
if img.0.len() > MAXIUMUM_FILE_SIZE {
return Json(Error::DataTooLong("image".to_string()).into());
}
// upload image
let mut bytes = Vec::new();
for byte in img.0 {
bytes.push(byte);
}
match save_avif_buffer(&path, bytes) {
Ok(_) => Json(ApiReturn {
ok: true,
message: "Avatar uploaded. It might take a bit to update".to_string(),
payload: (),
}),
Err(e) => Json(Error::MiscError(e.to_string()).into()),
}
}
/// Upload banner
pub async fn upload_banner_request(
jar: CookieJar,
Path(id): Path<usize>,
Extension(data): Extension<State>,
img: Image,
) -> impl IntoResponse {
// get user from token
let data = &(data.read().await).0;
let auth_user = match get_user_from_token!(jar, data) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
let community = match data.get_community_by_id(id).await {
Ok(c) => c,
Err(e) => return Json(e.into()),
};
if auth_user.id != community.owner {
if !auth_user
.permissions
.check(FinePermission::MANAGE_COMMUNITIES)
{
return Json(Error::NotAllowed.into());
}
}
let path = pathd!(
"{}/community_banners/{}.avif",
data.0.dirs.media,
&auth_user.id
);
// check file size
if img.0.len() > MAXIUMUM_FILE_SIZE {
return Json(Error::DataTooLong("image".to_string()).into());
}
// upload image
let mut bytes = Vec::new();
for byte in img.0 {
bytes.push(byte);
}
match save_avif_buffer(&path, bytes) {
Ok(_) => Json(ApiReturn {
ok: true,
message: "Banner uploaded. It might take a bit to update".to_string(),
payload: (),
}),
Err(e) => Json(Error::MiscError(e.to_string()).into()),
}
}

View file

@ -1,2 +1,3 @@
pub mod communities;
pub mod images;
pub mod posts;

View file

@ -4,13 +4,13 @@ use tetratto_core::model::{ApiReturn, Error, communities::Post};
use crate::{
State, get_user_from_token,
routes::api::v1::{CreateJournalEntry, UpdateJournalEntryContent, UpdateJournalEntryContext},
routes::api::v1::{CreatePost, UpdatePostContent, UpdatePostContext},
};
pub async fn create_request(
jar: CookieJar,
Extension(data): Extension<State>,
Json(req): Json<CreateJournalEntry>,
Json(req): Json<CreatePost>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data) {
@ -21,16 +21,26 @@ pub async fn create_request(
match data
.create_post(Post::new(
req.content,
req.journal,
req.replying_to,
match req.community.parse::<usize>() {
Ok(x) => x,
Err(e) => return Json(Error::MiscError(e.to_string()).into()),
},
if let Some(rt) = req.replying_to {
match rt.parse::<usize>() {
Ok(x) => Some(x),
Err(e) => return Json(Error::MiscError(e.to_string()).into()),
}
} else {
None
},
user.id,
))
.await
{
Ok(_) => Json(ApiReturn {
Ok(id) => Json(ApiReturn {
ok: true,
message: "Post created".to_string(),
payload: (),
payload: Some(id.to_string()),
}),
Err(e) => return Json(e.into()),
}
@ -61,7 +71,7 @@ pub async fn update_content_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
Json(req): Json<UpdateJournalEntryContent>,
Json(req): Json<UpdatePostContent>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data) {
@ -83,7 +93,7 @@ pub async fn update_context_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
Json(req): Json<UpdateJournalEntryContext>,
Json(req): Json<UpdatePostContext>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data) {

View file

@ -18,7 +18,11 @@ pub fn routes() -> Router {
.route("/reactions", post(reactions::create_request))
.route("/reactions/{id}", get(reactions::get_request))
.route("/reactions/{id}", delete(reactions::delete_request))
// journal journals
// communities
.route(
"/communities/find/{id}",
get(communities::communities::redirect_from_id),
)
.route(
"/communities",
post(communities::communities::create_request),
@ -36,13 +40,29 @@ pub fn routes() -> Router {
post(communities::communities::update_context_request),
)
.route(
"/journals/{id}/access/read",
"/communities/{id}/access/read",
post(communities::communities::update_read_access_request),
)
.route(
"/journals/{id}/access/write",
"/communities/{id}/access/write",
post(communities::communities::update_write_access_request),
)
.route(
"/communities/{id}/upload/avatar",
post(communities::images::upload_avatar_request),
)
.route(
"/communities/{id}/upload/banner",
post(communities::images::upload_banner_request),
)
.route(
"/communities/{id}/avatar",
get(communities::images::avatar_request),
)
.route(
"/communities/{id}/banner",
get(communities::images::banner_request),
)
// posts
.route("/posts", post(communities::posts::create_request))
.route("/posts/{id}", delete(communities::posts::delete_request))
@ -96,6 +116,10 @@ pub fn routes() -> Router {
"/auth/profile/{id}/verified",
post(auth::profile::update_profile_is_verified_request),
)
.route(
"/auth/profile/find/{id}",
get(auth::profile::redirect_from_id),
)
}
#[derive(Deserialize)]
@ -110,7 +134,7 @@ pub struct CreateCommunity {
}
#[derive(Deserialize)]
pub struct UpdateJournalTitle {
pub struct UpdateCommunityTitle {
pub title: String,
}
@ -120,30 +144,30 @@ pub struct UpdateCommunityContext {
}
#[derive(Deserialize)]
pub struct UpdateJournalReadAccess {
pub struct UpdateCommunityReadAccess {
pub access: CommunityReadAccess,
}
#[derive(Deserialize)]
pub struct UpdateJournalWriteAccess {
pub struct UpdateCommunityWriteAccess {
pub access: CommunityWriteAccess,
}
#[derive(Deserialize)]
pub struct CreateJournalEntry {
pub struct CreatePost {
pub content: String,
pub journal: usize,
pub community: String,
#[serde(default)]
pub replying_to: Option<usize>,
pub replying_to: Option<String>,
}
#[derive(Deserialize)]
pub struct UpdateJournalEntryContent {
pub struct UpdatePostContent {
pub content: String,
}
#[derive(Deserialize)]
pub struct UpdateJournalEntryContext {
pub struct UpdatePostContext {
pub context: PostContext,
}

View file

@ -1,11 +1,38 @@
use super::render_error;
use super::{PaginatedQuery, render_error};
use crate::{State, assets::initial_context, get_lang, get_user_from_token};
use axum::{
Extension,
extract::{Path, Query},
response::{Html, IntoResponse},
};
use axum_extra::extract::CookieJar;
use tetratto_core::model::Error;
use tera::Context;
use tetratto_core::model::{
Error,
auth::User,
communities::{Community, CommunityReadAccess},
};
macro_rules! check_permissions {
($community:ident, $jar:ident, $data:ident, $user:ident) => {
match $community.read_access {
CommunityReadAccess::Private => {
if let Some(ref ua) = $user {
if ua.id != $community.owner {
return Err(Html(
render_error(Error::NotAllowed, &$jar, &$data, &$user).await,
));
}
} else {
return Err(Html(
render_error(Error::NotAllowed, &$jar, &$data, &$user).await,
));
}
}
_ => (),
};
};
}
/// `/communities`
pub async fn list_request(jar: CookieJar, Extension(data): Extension<State>) -> impl IntoResponse {
@ -19,14 +46,22 @@ pub async fn list_request(jar: CookieJar, Extension(data): Extension<State>) ->
}
};
let posts = match data.0.get_memberships_by_owner(user.id).await {
let list = match data.0.get_memberships_by_owner(user.id).await {
Ok(p) => p,
Err(e) => return Err(Html(render_error(e, &jar, &data, &Some(user)).await)),
};
let mut communities: Vec<Community> = Vec::new();
for membership in &list {
match data.0.get_community_by_id(membership.community).await {
Ok(c) => communities.push(c),
Err(e) => return Err(Html(render_error(e, &jar, &data, &None).await)),
}
}
let lang = get_lang!(jar, data.0);
let mut context = initial_context(&data.0.0, lang, &Some(user)).await;
context.insert("posts", &posts);
context.insert("list", &communities);
// return
Ok(Html(
@ -35,3 +70,146 @@ pub async fn list_request(jar: CookieJar, Extension(data): Extension<State>) ->
.unwrap(),
))
}
pub fn community_context(
context: &mut Context,
community: &Community,
is_owner: bool,
is_joined: bool,
) {
context.insert("community", &community);
context.insert("is_owner", &is_owner);
context.insert("is_joined", &is_joined);
}
/// `/community/{title}`
pub async fn feed_request(
jar: CookieJar,
Path(title): Path<String>,
Query(props): Query<PaginatedQuery>,
Extension(data): Extension<State>,
) -> impl IntoResponse {
let data = data.read().await;
let user = get_user_from_token!(jar, data.0);
let community = match data.0.get_community_by_title(&title).await {
Ok(ua) => ua,
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
};
// check permissions
check_permissions!(community, jar, data, user);
// ...
let feed = match data
.0
.get_posts_by_community(community.id, 12, props.page)
.await
{
Ok(p) => match data.0.fill_posts(p).await {
Ok(p) => p,
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
},
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
};
// init context
let lang = get_lang!(jar, data.0);
let mut context = initial_context(&data.0.0, lang, &user).await;
let is_owner = if let Some(ref ua) = user {
ua.id == community.owner
} else {
false
};
let is_joined = if let Some(ref ua) = user {
data.0
.get_membership_by_owner_community(ua.id, community.id)
.await
.is_ok()
} else {
false
};
context.insert("feed", &feed);
community_context(&mut context, &community, is_owner, is_joined);
// return
Ok(Html(
data.1
.render("communities/feed.html", &mut context)
.unwrap(),
))
}
/// `/post/{id}`
pub async fn post_request(
jar: CookieJar,
Path(id): Path<usize>,
Query(props): Query<PaginatedQuery>,
Extension(data): Extension<State>,
) -> impl IntoResponse {
let data = data.read().await;
let user = get_user_from_token!(jar, data.0);
let post = match data.0.get_post_by_id(id).await {
Ok(ua) => ua,
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
};
let community = match data.0.get_community_by_id(post.community).await {
Ok(ua) => ua,
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
};
// check permissions
check_permissions!(community, jar, data, user);
// ...
let feed = match data.0.get_post_comments(post.id, 12, props.page).await {
Ok(p) => match data.0.fill_posts(p).await {
Ok(p) => p,
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
},
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
};
// init context
let lang = get_lang!(jar, data.0);
let mut context = initial_context(&data.0.0, lang, &user).await;
let is_owner = if let Some(ref ua) = user {
ua.id == community.owner
} else {
false
};
let is_joined = if let Some(ref ua) = user {
data.0
.get_membership_by_owner_community(ua.id, community.id)
.await
.is_ok()
} else {
false
};
context.insert("post", &post);
context.insert("replies", &feed);
context.insert(
"owner",
&data
.0
.get_user_by_id(post.owner)
.await
.unwrap_or(User::deleted()),
);
community_context(&mut context, &community, is_owner, is_joined);
// return
Ok(Html(
data.1
.render("communities/post.html", &mut context)
.unwrap(),
))
}

View file

@ -24,6 +24,8 @@ pub fn routes() -> Router {
.route("/user/{username}", get(profile::posts_request))
// communities
.route("/communities", get(communities::list_request))
.route("/community/{title}", get(communities::feed_request))
.route("/post/{id}", get(communities::post_request))
}
pub async fn render_error(

View file

@ -7,10 +7,17 @@ use axum::{
};
use axum_extra::extract::CookieJar;
use tera::Context;
use tetratto_core::model::{Error, auth::User};
use tetratto_core::model::{Error, auth::User, communities::Community};
pub fn profile_context(context: &mut Context, profile: &User, is_self: bool, is_following: bool) {
pub fn profile_context(
context: &mut Context,
profile: &User,
communities: &Vec<Community>,
is_self: bool,
is_following: bool,
) {
context.insert("profile", &profile);
context.insert("communities", &communities);
context.insert("is_self", &is_self);
context.insert("is_following", &is_following);
}
@ -30,15 +37,6 @@ pub async fn posts_request(
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
};
let posts = match data
.0
.get_posts_by_user(other_user.id, 12, props.page)
.await
{
Ok(p) => p,
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
};
// check if we're blocked
if let Some(ref ua) = user {
if data
@ -53,6 +51,27 @@ pub async fn posts_request(
}
}
// fetch data
let posts = match data
.0
.get_posts_by_user(other_user.id, 12, props.page)
.await
{
Ok(p) => match data.0.fill_posts_with_community(p).await {
Ok(p) => p,
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
},
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
};
let communities = match data.0.get_memberships_by_owner(other_user.id).await {
Ok(m) => match data.0.fill_communities(m).await {
Ok(m) => m,
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
},
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
};
// init context
let lang = get_lang!(jar, data.0);
let mut context = initial_context(&data.0.0, lang, &user).await;
@ -73,7 +92,13 @@ pub async fn posts_request(
};
context.insert("posts", &posts);
profile_context(&mut context, &other_user, is_self, is_following);
profile_context(
&mut context,
&other_user,
&communities,
is_self,
is_following,
);
// return
Ok(Html(