add reposts/quotes

fix #2
This commit is contained in:
trisua 2025-04-10 18:16:52 -04:00
parent 15e24b9a61
commit df32b9d65e
43 changed files with 708 additions and 234 deletions

9
Cargo.lock generated
View file

@ -3155,8 +3155,9 @@ dependencies = [
[[package]] [[package]]
name = "tetratto" name = "tetratto"
version = "1.0.1" version = "1.0.2"
dependencies = [ dependencies = [
"ammonia",
"axum", "axum",
"axum-extra", "axum-extra",
"cf-turnstile", "cf-turnstile",
@ -3179,7 +3180,7 @@ dependencies = [
[[package]] [[package]]
name = "tetratto-core" name = "tetratto-core"
version = "1.0.1" version = "1.0.2"
dependencies = [ dependencies = [
"async-recursion", "async-recursion",
"bb8-postgres", "bb8-postgres",
@ -3198,7 +3199,7 @@ dependencies = [
[[package]] [[package]]
name = "tetratto-l10n" name = "tetratto-l10n"
version = "1.0.1" version = "1.0.2"
dependencies = [ dependencies = [
"pathbufd", "pathbufd",
"serde", "serde",
@ -3207,7 +3208,7 @@ dependencies = [
[[package]] [[package]]
name = "tetratto-shared" name = "tetratto-shared"
version = "1.0.1" version = "1.0.2"
dependencies = [ dependencies = [
"ammonia", "ammonia",
"chrono", "chrono",

View file

@ -1,6 +1,6 @@
[package] [package]
name = "tetratto" name = "tetratto"
version = "1.0.1" version = "1.0.2"
edition = "2024" edition = "2024"
[features] [features]
@ -19,6 +19,7 @@ tower-http = { version = "0.6.2", features = ["trace", "fs"] }
axum = { version = "0.8.3", features = ["macros"] } axum = { version = "0.8.3", features = ["macros"] }
tokio = { version = "1.44.2", features = ["macros", "rt-multi-thread"] } tokio = { version = "1.44.2", features = ["macros", "rt-multi-thread"] }
axum-extra = { version = "0.10.1", features = ["cookie", "multipart"] } axum-extra = { version = "0.10.1", features = ["cookie", "multipart"] }
ammonia = "4.0.0"
tetratto-shared = { path = "../shared" } tetratto-shared = { path = "../shared" }
tetratto-core = { path = "../core", features = [ tetratto-core = { path = "../core", features = [
"redis", "redis",

View file

@ -71,7 +71,10 @@ pub fn save_avif_buffer(path: &str, bytes: Vec<u8>) -> std::io::Result<()> {
let file = File::create(path)?; let file = File::create(path)?;
let mut writer = BufWriter::new(file); let mut writer = BufWriter::new(file);
if let Err(_) = pre_img_buffer.write_to(&mut writer, image::ImageFormat::Avif) { if pre_img_buffer
.write_to(&mut writer, image::ImageFormat::Avif)
.is_err()
{
return Err(std::io::Error::new( return Err(std::io::Error::new(
std::io::ErrorKind::Other, std::io::ErrorKind::Other,
"Image conversion failed", "Image conversion failed",

View file

@ -18,6 +18,8 @@ version = "1.0.0"
"general:action.back" = "Back" "general:action.back" = "Back"
"general:action.report" = "Report" "general:action.report" = "Report"
"general:action.manage" = "Manage" "general:action.manage" = "Manage"
"general:label.safety" = "Safety"
"general:label.share" = "Share"
"general:action.add_account" = "Add account" "general:action.add_account" = "Add account"
"general:action.switch_account" = "Switch account" "general:action.switch_account" = "Switch account"
"general:label.mod" = "Mod" "general:label.mod" = "Mod"
@ -75,6 +77,9 @@ version = "1.0.0"
"communities:label.new_title" = "New title" "communities:label.new_title" = "New title"
"communities:label.pinned" = "Pinned" "communities:label.pinned" = "Pinned"
"communities:label.edit_content" = "Edit content" "communities:label.edit_content" = "Edit content"
"communities:label.repost" = "Repost"
"communities:label.quote_post" = "Quote post"
"communities:label.expand_original" = "Expand original"
"notifs:action.mark_as_read" = "Mark as read" "notifs:action.mark_as_read" = "Mark as read"
"notifs:action.mark_as_unread" = "Mark as unread" "notifs:action.mark_as_unread" = "Mark as unread"

View file

@ -2,6 +2,7 @@ mod assets;
mod avif; mod avif;
mod macros; mod macros;
mod routes; mod routes;
mod sanitize;
use assets::{init_dirs, write_assets}; use assets::{init_dirs, write_assets};
pub use tetratto_core::*; pub use tetratto_core::*;

View file

@ -524,6 +524,7 @@ select {
resize: vertical; resize: vertical;
width: 100%; width: 100%;
font-family: inherit; font-family: inherit;
font-size: 16px;
/* personality */ /* personality */
background: transparent; background: transparent;
color: inherit; color: inherit;

View file

@ -42,7 +42,11 @@
<div class="card flex flex-col gap-4"> <div class="card flex flex-col gap-4">
<!-- prettier-ignore --> <!-- prettier-ignore -->
{% for post in pinned %} {% for post in pinned %}
{{ components::post(post=post[0], owner=post[1], secondary=true, show_community=false, can_manage_post=can_manage_posts) }} {% if post[0].context.repost and post[0].context.repost.reposting %}
{{ components::repost(repost=post[2], post=post[0], owner=post[1], secondary=true, show_community=false, can_manage_post=can_manage_posts) }}
{% else %}
{{ components::post(post=post[0], owner=post[1], secondary=true, show_community=false, can_manage_post=can_manage_posts) }}
{% endif %}
{% endfor %} {% endfor %}
</div> </div>
</div> </div>
@ -57,7 +61,11 @@
<div class="card flex flex-col gap-4"> <div class="card flex flex-col gap-4">
<!-- prettier-ignore --> <!-- prettier-ignore -->
{% for post in feed %} {% for post in feed %}
{{ components::post(post=post[0], owner=post[1], secondary=true, show_community=false, can_manage_post=can_manage_posts) }} {% if post[0].context.repost and post[0].context.repost.reposting %}
{{ components::repost(repost=post[2], post=post[0], owner=post[1], secondary=true, show_community=false, can_manage_post=can_manage_posts) }}
{% else %}
{{ components::post(post=post[0], owner=post[1], secondary=true, show_community=false, can_manage_post=can_manage_posts) }}
{% endif %}
{% endfor %} {% endfor %}
{{ components::pagination(page=page, items=feed|length) }} {{ components::pagination(page=page, items=feed|length) }}

View file

@ -7,9 +7,18 @@
{{ icon "arrow-up" }} {{ icon "arrow-up" }}
<span>{{ text "communities:action.continue_thread" }}</span> <span>{{ text "communities:action.continue_thread" }}</span>
</a> </a>
{% endif %} {{ components::post(post=post, owner=owner, community=community, {% endif %}
show_community=true, can_manage_post=can_manage_posts) }} {% if user and
post.context.comments_enabled %} <!-- prettier-ignore -->
<div style="display: contents;">
{% if post.context.repost and post.context.repost.reposting %}
{{ components::repost(repost=reposting, post=post, owner=owner, community=community, show_community=true, can_manage_post=can_manage_posts) }}
{% else %}
{{ components::post(post=post, owner=owner, community=community, show_community=true, can_manage_post=can_manage_posts) }}
{% endif %}
</div>
{% if user and post.context.comments_enabled %}
<div class="card-nest"> <div class="card-nest">
<div class="card small"> <div class="card small">
<b>{{ text "communities:label.create_reply" }}</b> <b>{{ text "communities:label.create_reply" }}</b>
@ -116,6 +125,11 @@
"{{ post.context.comments_enabled }}", "{{ post.context.comments_enabled }}",
"checkbox", "checkbox",
], ],
[
["reposts_enabled", "Allow people to repost your post"],
"{{ post.context.reposts_enabled }}",
"checkbox",
],
[ [
["is_nsfw", "Mark as NSFW"], ["is_nsfw", "Mark as NSFW"],
"{{ community.context.is_nsfw }}", "{{ community.context.is_nsfw }}",

View file

@ -396,10 +396,15 @@
}, 250); }, 250);
</script> </script>
<!-- prettier-ignore -->
<script type="application/json" id="settings_json">{{ community_context_serde|safe }}</script>
<script> <script>
setTimeout(() => { setTimeout(() => {
const ui = ns("ui"); const ui = ns("ui");
const settings = JSON.parse("{{ community_context_serde|safe }}"); const settings = JSON.parse(
document.getElementById("settings_json").innerHTML,
);
globalThis.upload_avatar = (e) => { globalThis.upload_avatar = (e) => {
e.preventDefault(); e.preventDefault();

View file

@ -104,6 +104,45 @@ community %}
</span> </span>
{% endif %} {% endif %}
</div> </div>
{%- endmacro %} {% macro repost(repost, post, owner, secondary=false,
community=false, show_community=true, can_manage_post=false) -%}
<div style="display: contents">
<!-- prettier-ignore -->
<div style="display: none" id="repost-content:{{ post.id }}">
{% if repost %}
{{ components::post(post=repost[1], owner=repost[0], secondary=not secondary, community=false, show_community=false, can_manage_post=false) }}
{% else %}
<div class="card tertiary red flex items-center gap-2">
{{ icon "frown" }}
<span>Could not find original post...</span>
</div>
{% endif %}
</div>
{{ components::post(post=post, owner=owner, secondary=secondary,
community=community, show_community=show_community,
can_manage_post=can_manage_post) }}
<script>
document.getElementById("post-content:{{ post.id }}").innerHTML +=
document.getElementById("repost-content:{{ post.id }}").innerHTML;
document.getElementById("repost-content:{{ post.id }}").remove();
document
.getElementById("post:{{ post.id }}")
.querySelector(".avatar")
.setAttribute("style", "--size: 24px");
document
.getElementById("post:{{ post.id }}")
.querySelector(".name")
.parentElement.prepend(
document
.getElementById("post:{{ post.id }}")
.querySelector(".avatar"),
);
</script>
</div>
{%- endmacro %} {% macro post(post, owner, secondary=false, community=false, {%- endmacro %} {% macro post(post, owner, secondary=false, community=false,
show_community=true, can_manage_post=false) -%} {% if community and show_community=true, can_manage_post=false) -%} {% if community and
show_community and post.community != config.town_square %} show_community and post.community != config.town_square %}
@ -130,6 +169,7 @@ show_community and post.community != config.town_square %}
{% endif %} {% endif %}
<div <div
class="card flex flex-col gap-2 {% if secondary %}secondary{% endif %}" class="card flex flex-col gap-2 {% if secondary %}secondary{% endif %}"
id="post:{{ post.id }}"
> >
<div class="w-full flex gap-2"> <div class="w-full flex gap-2">
<a href="/@{{ owner.username }}"> <a href="/@{{ owner.username }}">
@ -150,13 +190,6 @@ show_community and post.community != config.town_square %}
</div> </div>
{% else %} {% else %}
<span class="fade date">{{ post.created }}</span> <span class="fade date">{{ post.created }}</span>
{% endif %} {% if show_community %}
<a href="/api/v1/communities/find/{{ post.community }}">
<!-- prettier-ignore -->
{% if not community %}
{{ components::community_avatar(id=post.community) }}
{% endif %}
</a>
{% endif %} {% if post.context.is_nsfw %} {% endif %} {% if post.context.is_nsfw %}
<span <span
title="NSFW post" title="NSFW post"
@ -165,6 +198,15 @@ show_community and post.community != config.town_square %}
> >
{{ icon "square-asterisk" }} {{ icon "square-asterisk" }}
</span> </span>
{% endif %} {% if post.context.repost and
post.context.repost.reposting %}
<span
title="Repost"
class="flex items-center"
style="color: var(--color-primary)"
>
{{ icon "repeat-2" }}
</span>
{% endif %} {% endif %}
</div> </div>
@ -175,7 +217,16 @@ show_community and post.community != config.town_square %}
</div> </div>
<div class="flex justify-between items-center gap-2 w-full"> <div class="flex justify-between items-center gap-2 w-full">
{% if user %} {% if user %} {% if post.context.repost and
post.context.repost.reposting %}
<a
href="/post/{{ post.context.repost.reposting }}"
class="button small camo"
>
{{ icon "expand" }}
<span>{{ text "communities:label.expand_original" }}</span>
</a>
{% else %}
<div <div
class="flex gap-1 reactions_box" class="flex gap-1 reactions_box"
hook="check_reactions" hook="check_reactions"
@ -184,7 +235,7 @@ show_community and post.community != config.town_square %}
{{ components::likes(id=post.id, asset_type="Post", {{ components::likes(id=post.id, asset_type="Post",
likes=post.likes, dislikes=post.dislikes) }} likes=post.likes, dislikes=post.dislikes) }}
</div> </div>
{% else %} {% endif %} {% else %}
<div></div> <div></div>
{% endif %} {% endif %}
@ -213,7 +264,26 @@ show_community and post.community != config.town_square %}
</button> </button>
<div class="inner"> <div class="inner">
{% if user.id != post.owner %} {% if config.town_square and
post.context.reposts_enabled %}
<b class="title">{{ text "general:label.share" }}</b>
<button
onclick="trigger('me::repost', ['{{ post.id }}', '', '{{ config.town_square }}'])"
>
{{ icon "repeat-2" }}
<span>{{ text "communities:label.repost" }}</span>
</button>
<button
onclick="window.REPOST_ID = '{{ post.id }}'; document.getElementById('quote_dialog').showModal()"
>
{{ icon "quote" }}
<span
>{{ text "communities:label.quote_post" }}</span
>
</button>
{% endif %} {% if user.id != post.owner %}
<b class="title">{{ text "general:label.safety" }}</b>
<button <button
class="red" class="red"
onclick="trigger('me::report', ['{{ post.id }}', 'post'])" onclick="trigger('me::report', ['{{ post.id }}', 'post'])"
@ -483,4 +553,46 @@ user.settings.theme_hue %}
match_user_theme(); match_user_theme();
}, 150); }, 150);
</script> </script>
{% endif %} {% endif %} {% endif %} {%- endmacro %} {% endif %} {% endif %} {% endif %} {%- endmacro %} {% macro quote_form() -%} {%
if config.town_square and user %}
<div class="card-nest">
<div class="card small flex flex-col">
<div class="flex items-center gap-2">
{{ icon "quote" }}
<span>{{ text "communities:label.quote_post" }}</span>
</div>
</div>
<form
class="card flex flex-col gap-2"
onsubmit="create_repost_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>
<script>
async function create_repost_from_form(e) {
e.preventDefault();
await trigger("atto::debounce", ["posts::create"]);
await trigger("me::repost", [
window.REPOST_ID,
e.target.content.value,
"{{ config.town_square }}",
]);
}
</script>
{% endif %} {%- endmacro %}

View file

@ -67,7 +67,10 @@
</div> </div>
</div> </div>
<div class="card flex flex-col gap-2" id="social"> <div
class="card flex flex-col items-center gap-2"
id="social"
>
<div class="w-full flex"> <div class="w-full flex">
<a <a
href="/@{{ profile.username }}/followers" href="/@{{ profile.username }}/followers"
@ -84,6 +87,15 @@
<span>{{ text "auth:label.following" }}</span> <span>{{ text "auth:label.following" }}</span>
</a> </a>
</div> </div>
{% if is_following_you %}
<b
class="notification chip w-content flex items-center gap-2"
>
{{ icon "heart" }}
<span>Follows you</span>
</b>
{% endif %}
</div> </div>
</div> </div>

View file

@ -9,7 +9,11 @@
<div class="card flex flex-col gap-4"> <div class="card flex flex-col gap-4">
<!-- prettier-ignore --> <!-- prettier-ignore -->
{% for post in pinned %} {% for post in pinned %}
{{ components::post(post=post[0], owner=post[1], secondary=true, community=post[2], show_community=true, can_manage_post=is_self) }} {% if post[0].context.repost and post[0].context.repost.reposting %}
{{ components::repost(repost=post[3], post=post[0], owner=post[1], secondary=true, community=post[2], show_community=true, can_manage_post=is_self) }}
{% else %}
{{ components::post(post=post[0], owner=post[1], secondary=true, community=post[2], can_manage_post=is_self) }}
{% endif %}
{% endfor %} {% endfor %}
</div> </div>
</div> </div>
@ -24,7 +28,11 @@
<div class="card flex flex-col gap-4"> <div class="card flex flex-col gap-4">
<!-- prettier-ignore --> <!-- prettier-ignore -->
{% for post in posts %} {% for post in posts %}
{{ components::post(post=post[0], owner=post[1], secondary=true, community=post[2], show_community=true, can_manage_post=is_self) }} {% if post[0].context.repost and post[0].context.repost.reposting %}
{{ components::repost(repost=post[3], post=post[0], owner=post[1], secondary=true, community=post[2], show_community=true, can_manage_post=is_self) }}
{% else %}
{{ components::post(post=post[0], owner=post[1], secondary=true, community=post[2], can_manage_post=is_self) }}
{% endif %}
{% endfor %} {% endfor %}
{{ components::pagination(page=page, items=posts|length) }} {{ components::pagination(page=page, items=posts|length) }}

View file

@ -326,10 +326,15 @@
{% endfor %} {% endfor %}
</div> </div>
<!-- prettier-ignore -->
<script type="application/json" id="settings_json">{{ user_settings_serde|safe }}</script>
<script> <script>
setTimeout(() => { setTimeout(() => {
const ui = ns("ui"); const ui = ns("ui");
const settings = JSON.parse("{{ user_settings_serde|safe }}"); const settings = JSON.parse(
document.getElementById("settings_json").innerHTML,
);
let tokens = JSON.parse("{{ user_tokens_serde|safe }}"); let tokens = JSON.parse("{{ user_tokens_serde|safe }}");
globalThis.remove_token = async (id) => { globalThis.remove_token = async (id) => {

View file

@ -317,6 +317,26 @@ macros -%}
</div> </div>
</div> </div>
</dialog> </dialog>
<dialog id="quote_dialog">
<div class="inner flex flex-col gap-2">
{{ components::quote_form() }}
<div class="flex justify-between">
<div></div>
<div class="flex gap-2">
<button
class="bold red quaternary"
onclick="document.getElementById('quote_dialog').close()"
type="button"
>
{{ icon "x" }} {{ text "dialog:action.close" }}
</button>
</div>
</div>
</div>
</dialog>
{% endif %} {% if user and use_user_theme %} {{ {% endif %} {% if user and use_user_theme %} {{
components::theme(user=user) }} {% endif %} components::theme(user=user) }} {% endif %}
</body> </body>

View file

@ -7,7 +7,11 @@
<!-- prettier-ignore --> <!-- prettier-ignore -->
<div class="card w-full flex flex-col gap-2"> <div class="card w-full flex flex-col gap-2">
{% for post in list %} {% for post in list %}
{{ components::post(post=post[0], owner=post[1], secondary=true, community=post[2], show_community=true) }} {% if post[0].context.repost and post[0].context.repost.reposting %}
{{ components::repost(repost=post[3], post=post[0], owner=post[1], secondary=true, community=post[2], show_community=true) }}
{% else %}
{{ components::post(post=post[0], owner=post[1], secondary=true, community=post[2]) }}
{% endif %}
{% endfor %} {% endfor %}
{{ components::pagination(page=page, items=list|length) }} {{ components::pagination(page=page, items=list|length) }}

View file

@ -19,7 +19,11 @@
<!-- prettier-ignore --> <!-- prettier-ignore -->
<div class="card w-full flex flex-col gap-2"> <div class="card w-full flex flex-col gap-2">
{% for post in list %} {% for post in list %}
{{ components::post(post=post[0], owner=post[1], secondary=true, community=post[2], show_community=true) }} {% if post[0].context.repost and post[0].context.repost.reposting %}
{{ components::repost(repost=post[3], post=post[0], owner=post[1], secondary=true, community=post[2], show_community=true) }}
{% else %}
{{ components::post(post=post[0], owner=post[1], secondary=true, community=post[2]) }}
{% endif %}
{% endfor %} {% endfor %}
{{ components::pagination(page=page, items=list|length) }} {{ components::pagination(page=page, items=list|length) }}

View file

@ -7,7 +7,11 @@
<!-- prettier-ignore --> <!-- prettier-ignore -->
<div class="card w-full flex flex-col gap-2"> <div class="card w-full flex flex-col gap-2">
{% for post in list %} {% for post in list %}
{{ components::post(post=post[0], owner=post[1], secondary=true, community=post[2], show_community=true) }} {% if post[0].context.repost and post[0].context.repost.reposting %}
{{ components::repost(repost=post[3], post=post[0], owner=post[1], secondary=true, community=post[2], show_community=true) }}
{% else %}
{{ components::post(post=post[0], owner=post[1], secondary=true, community=post[2]) }}
{% endif %}
{% endfor %} {% endfor %}
{{ components::pagination(page=page, items=list|length) }} {{ components::pagination(page=page, items=list|length) }}

View file

@ -149,6 +149,32 @@
}); });
}); });
self.define("repost", (_, id, content, community) => {
fetch(`/api/v1/posts/${id}/repost`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
content,
community,
}),
})
.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);
}
});
});
self.define("report", (_, asset, asset_type) => { self.define("report", (_, asset, asset_type) => {
window.open( window.open(
`/mod_panel/file_report?asset=${asset}&asset_type=${asset_type}`, `/mod_panel/file_report?asset=${asset}&asset_type=${asset_type}`,

View file

@ -50,7 +50,7 @@ pub async fn register_request(
.to_string(); .to_string();
// check for ip ban // check for ip ban
if let Ok(_) = data.get_ipban_by_ip(&real_ip).await { if data.get_ipban_by_ip(&real_ip).await.is_ok() {
return (None, Json(Error::NotAllowed.into())); return (None, Json(Error::NotAllowed.into()));
} }
@ -126,7 +126,7 @@ pub async fn login_request(
.to_string(); .to_string();
// check for ip ban // check for ip ban
if let Ok(_) = data.get_ipban_by_ip(&real_ip).await { if data.get_ipban_by_ip(&real_ip).await.is_ok() {
return (None, Json(Error::NotAllowed.into())); return (None, Json(Error::NotAllowed.into()));
} }

View file

@ -330,7 +330,7 @@ pub async fn disable_totp_request(
} }
// ... // ...
match data.update_user_totp(id, &String::new(), &Vec::new()).await { match data.update_user_totp(id, "", &Vec::new()).await {
Ok(()) => Json(ApiReturn { Ok(()) => Json(ApiReturn {
ok: true, ok: true,
message: "TOTP disabled".to_string(), message: "TOTP disabled".to_string(),

View file

@ -3,8 +3,9 @@ use axum_extra::extract::CookieJar;
use tetratto_core::model::{ApiReturn, Error, communities::Post}; use tetratto_core::model::{ApiReturn, Error, communities::Post};
use crate::{ use crate::{
State, get_user_from_token, get_user_from_token,
routes::api::v1::{CreatePost, UpdatePostContent, UpdatePostContext}, routes::api::v1::{CreatePost, CreateRepost, UpdatePostContent, UpdatePostContext},
State,
}; };
pub async fn create_request( pub async fn create_request(
@ -46,6 +47,39 @@ pub async fn create_request(
} }
} }
pub async fn create_repost_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
Json(req): Json<CreateRepost>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
match data
.create_post(Post::repost(
req.content,
match req.community.parse::<usize>() {
Ok(x) => x,
Err(e) => return Json(Error::MiscError(e.to_string()).into()),
},
user.id,
id,
))
.await
{
Ok(id) => Json(ApiReturn {
ok: true,
message: "Post reposted".to_string(),
payload: Some(id.to_string()),
}),
Err(e) => Json(e.into()),
}
}
pub async fn delete_request( pub async fn delete_request(
jar: CookieJar, jar: CookieJar,
Extension(data): Extension<State>, Extension(data): Extension<State>,

View file

@ -81,6 +81,10 @@ pub fn routes() -> Router {
// posts // posts
.route("/posts", post(communities::posts::create_request)) .route("/posts", post(communities::posts::create_request))
.route("/posts/{id}", delete(communities::posts::delete_request)) .route("/posts/{id}", delete(communities::posts::delete_request))
.route(
"/posts/{id}/repost",
post(communities::posts::create_repost_request),
)
.route( .route(
"/posts/{id}/content", "/posts/{id}/content",
post(communities::posts::update_content_request), post(communities::posts::update_content_request),
@ -247,6 +251,12 @@ pub struct CreatePost {
pub replying_to: Option<String>, pub replying_to: Option<String>,
} }
#[derive(Deserialize)]
pub struct CreateRepost {
pub content: String,
pub community: String,
}
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct UpdatePostContent { pub struct UpdatePostContent {
pub content: String, pub content: String,

View file

@ -1,5 +1,5 @@
use super::{PaginatedQuery, render_error}; use super::{PaginatedQuery, render_error};
use crate::{State, assets::initial_context, get_lang, get_user_from_token}; use crate::{assets::initial_context, get_lang, get_user_from_token, sanitize::clean_context, State};
use axum::{ use axum::{
Extension, Extension,
extract::{Path, Query}, extract::{Path, Query},
@ -323,9 +323,7 @@ pub async fn settings_request(
context.insert("community", &community); context.insert("community", &community);
context.insert( context.insert(
"community_context_serde", "community_context_serde",
&serde_json::to_string(&community.context) &clean_context(&community.context),
.unwrap()
.replace("\"", "\\\""),
); );
// return // return
@ -347,15 +345,38 @@ pub async fn post_request(
let user = get_user_from_token!(jar, data.0); let user = get_user_from_token!(jar, data.0);
let post = match data.0.get_post_by_id(id).await { let post = match data.0.get_post_by_id(id).await {
Ok(ua) => ua, 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 community = match data.0.get_community_by_id(post.community).await { let community = match data.0.get_community_by_id(post.community).await {
Ok(ua) => ua, Ok(c) => c,
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)), Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
}; };
// check repost
let reposting = if let Some(ref repost) = post.context.repost {
if let Some(reposting) = repost.reposting {
let mut x = match data.0.get_post_by_id(reposting).await {
Ok(p) => p,
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
};
x.mark_as_repost();
Some((
match data.0.get_user_by_id(x.owner).await {
Ok(ua) => ua,
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
},
x,
))
} else {
None
}
} else {
None
};
// check permissions // check permissions
let (can_read, can_manage_pins) = check_permissions!(community, jar, data, user); let (can_read, can_manage_pins) = check_permissions!(community, jar, data, user);
@ -383,6 +404,7 @@ pub async fn post_request(
) = community_context_bools!(data, user, community); ) = community_context_bools!(data, user, community);
context.insert("post", &post); context.insert("post", &post);
context.insert("reposting", &reposting);
context.insert("replies", &feed); context.insert("replies", &feed);
context.insert("page", &props.page); context.insert("page", &props.page);
context.insert( context.insert(

View file

@ -47,7 +47,7 @@ pub async fn index_request(
.get_posts_from_user_communities(user.id, 12, req.page) .get_posts_from_user_communities(user.id, 12, req.page)
.await .await
{ {
Ok(l) => match data.0.fill_posts_with_community(l).await { Ok(l) => match data.0.fill_posts_with_community(l, user.id).await {
Ok(l) => l, Ok(l) => l,
Err(e) => return Html(render_error(e, &jar, &data, &Some(user)).await), Err(e) => return Html(render_error(e, &jar, &data, &Some(user)).await),
}, },
@ -83,7 +83,7 @@ pub async fn following_request(
.get_posts_from_user_following(user.id, 12, req.page) .get_posts_from_user_following(user.id, 12, req.page)
.await .await
{ {
Ok(l) => match data.0.fill_posts_with_community(l).await { Ok(l) => match data.0.fill_posts_with_community(l, user.id).await {
Ok(l) => l, Ok(l) => l,
Err(e) => return Err(Html(render_error(e, &jar, &data, &Some(user)).await)), Err(e) => return Err(Html(render_error(e, &jar, &data, &Some(user)).await)),
}, },
@ -110,7 +110,11 @@ pub async fn popular_request(
let user = get_user_from_token!(jar, data.0); let user = get_user_from_token!(jar, data.0);
let list = match data.0.get_popular_posts(12, req.page).await { let list = match data.0.get_popular_posts(12, req.page).await {
Ok(l) => match data.0.fill_posts_with_community(l).await { Ok(l) => match data
.0
.fill_posts_with_community(l, if let Some(ref ua) = user { ua.id } else { 0 })
.await
{
Ok(l) => l, Ok(l) => l,
Err(e) => return Html(render_error(e, &jar, &data, &user).await), Err(e) => return Html(render_error(e, &jar, &data, &user).await),
}, },

View file

@ -1,5 +1,5 @@
use super::{PaginatedQuery, render_error}; use super::{PaginatedQuery, render_error};
use crate::{State, assets::initial_context, get_lang, get_user_from_token}; use crate::{assets::initial_context, get_lang, get_user_from_token, sanitize::clean_settings, State};
use axum::{ use axum::{
Extension, Extension,
extract::{Path, Query}, extract::{Path, Query},
@ -44,19 +44,13 @@ pub async fn settings_request(
} }
}; };
let settings = profile.settings.clone();
let tokens = profile.tokens.clone(); let tokens = profile.tokens.clone();
let lang = get_lang!(jar, data.0); let lang = get_lang!(jar, data.0);
let mut context = initial_context(&data.0.0, lang, &Some(user)).await; let mut context = initial_context(&data.0.0, lang, &Some(user)).await;
context.insert("profile", &profile); context.insert("profile", &profile);
context.insert( context.insert("user_settings_serde", &clean_settings(&profile.settings));
"user_settings_serde",
&serde_json::to_string(&settings)
.unwrap()
.replace("\"", "\\\""),
);
context.insert( context.insert(
"user_tokens_serde", "user_tokens_serde",
&serde_json::to_string(&tokens) &serde_json::to_string(&tokens)
@ -158,7 +152,11 @@ pub async fn posts_request(
.get_posts_by_user(other_user.id, 12, props.page) .get_posts_by_user(other_user.id, 12, props.page)
.await .await
{ {
Ok(p) => match data.0.fill_posts_with_community(p).await { Ok(p) => match data
.0
.fill_posts_with_community(p, if let Some(ref ua) = user { ua.id } else { 0 })
.await
{
Ok(p) => p, 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)),
}, },
@ -166,7 +164,11 @@ pub async fn posts_request(
}; };
let pinned = match data.0.get_pinned_posts_by_user(other_user.id).await { let pinned = match data.0.get_pinned_posts_by_user(other_user.id).await {
Ok(p) => match data.0.fill_posts_with_community(p).await { Ok(p) => match data
.0
.fill_posts_with_community(p, if let Some(ref ua) = user { ua.id } else { 0 })
.await
{
Ok(p) => p, 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)),
}, },
@ -219,8 +221,8 @@ pub async fn posts_request(
}; };
context.insert("posts", &posts); context.insert("posts", &posts);
context.insert("page", &props.page);
context.insert("pinned", &pinned); context.insert("pinned", &pinned);
context.insert("page", &props.page);
profile_context( profile_context(
&mut context, &mut context,
&user, &user,

View file

@ -0,0 +1,82 @@
use ammonia::Builder;
use tetratto_core::model::{auth::UserSettings, communities::CommunityContext};
/// Escape profile colors
// pub fn color_escape(color: &&&String) -> String {
// remove_tags(
// &color
// .replace(";", "")
// .replace("<", "&lt;")
// .replace(">", "%gt;")
// .replace("}", "")
// .replace("{", "")
// .replace("url(\"", "url(\"/api/v0/util/ext/image?img=")
// .replace("url('", "url('/api/v0/util/ext/image?img=")
// .replace("url(https://", "url(/api/v0/util/ext/image?img=https://"),
// )
// }
/// Clean profile metadata
pub fn remove_tags(input: &str) -> String {
Builder::default()
.rm_tags(&["img", "a", "span", "p", "h1", "h2", "h3", "h4", "h5", "h6"])
.clean(input)
.to_string()
.replace("&lt;", "<")
.replace("&gt;", ">")
.replace("&amp;", "&")
.replace("</script>", "</not-script")
}
fn clean_single(input: &str) -> String {
input
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("url(\"", "url(\"/api/v0/util/ext/image?img=")
.replace("url(https://", "url(/api/v0/util/ext/image?img=https://")
.replace("<style>", "")
.replace("</style>", "")
}
/// Clean user settings
pub fn clean_settings(settings: &UserSettings) -> String {
remove_tags(&serde_json::to_string(&clean_settings_raw(settings)).unwrap())
.replace("\u{200d}", "")
// how do you end up with these in your settings?
.replace("\u{0010}", "")
.replace("\u{0011}", "")
.replace("\u{0012}", "")
.replace("\u{0013}", "")
.replace("\u{0014}", "")
}
/// Clean user settings row
pub fn clean_settings_raw(settings: &UserSettings) -> UserSettings {
let mut settings = settings.to_owned();
settings.biography = clean_single(&settings.biography);
settings.theme_hue = clean_single(&settings.theme_hue);
settings.theme_sat = clean_single(&settings.theme_sat);
settings.theme_lit = clean_single(&settings.theme_lit);
settings
}
/// Clean community context
pub fn clean_context(context: &CommunityContext) -> String {
remove_tags(&serde_json::to_string(&clean_context_raw(context)).unwrap())
.replace("\u{200d}", "")
// how do you end up with these in your settings?
.replace("\u{0010}", "")
.replace("\u{0011}", "")
.replace("\u{0012}", "")
.replace("\u{0013}", "")
.replace("\u{0014}", "")
}
/// Clean community context row
pub fn clean_context_raw(context: &CommunityContext) -> CommunityContext {
let mut context = context.to_owned();
context.description = clean_single(&context.description);
context
}

View file

@ -1,6 +1,6 @@
[package] [package]
name = "tetratto-core" name = "tetratto-core"
version = "1.0.1" version = "1.0.2"
edition = "2024" edition = "2024"
[features] [features]

View file

@ -34,11 +34,7 @@ impl DataManager {
settings: serde_json::from_str(&get!(x->5(String)).to_string()).unwrap(), settings: serde_json::from_str(&get!(x->5(String)).to_string()).unwrap(),
tokens: serde_json::from_str(&get!(x->6(String)).to_string()).unwrap(), tokens: serde_json::from_str(&get!(x->6(String)).to_string()).unwrap(),
permissions: FinePermission::from_bits(get!(x->7(i32)) as u32).unwrap(), permissions: FinePermission::from_bits(get!(x->7(i32)) as u32).unwrap(),
is_verified: if get!(x->8(i32)) as i8 == 1 { is_verified: get!(x->8(i32)) as i8 == 1,
true
} else {
false
},
notification_count: get!(x->9(i32)) as usize, notification_count: get!(x->9(i32)) as usize,
follower_count: get!(x->10(i32)) as usize, follower_count: get!(x->10(i32)) as usize,
following_count: get!(x->11(i32)) as usize, following_count: get!(x->11(i32)) as usize,
@ -80,7 +76,7 @@ impl DataManager {
/// # Arguments /// # Arguments
/// * `data` - a mock [`User`] object to insert /// * `data` - a mock [`User`] object to insert
pub async fn create_user(&self, mut data: User) -> Result<()> { pub async fn create_user(&self, mut data: User) -> Result<()> {
if self.0.security.registration_enabled == false { if !self.0.security.registration_enabled {
return Err(Error::RegistrationDisabled); return Err(Error::RegistrationDisabled);
} }
@ -124,10 +120,10 @@ impl DataManager {
&serde_json::to_string(&data.settings).unwrap(), &serde_json::to_string(&data.settings).unwrap(),
&serde_json::to_string(&data.tokens).unwrap(), &serde_json::to_string(&data.tokens).unwrap(),
&(FinePermission::DEFAULT.bits() as i32), &(FinePermission::DEFAULT.bits() as i32),
&(if data.is_verified { 1 as i32 } else { 0 as i32 }), &(if data.is_verified { 1_i32 } else { 0_i32 }),
&(0 as i32), &0_i32,
&(0 as i32), &0_i32,
&(0 as i32), &0_i32,
&(data.last_seen as i64), &(data.last_seen as i64),
&String::new(), &String::new(),
&"[]" &"[]"
@ -260,7 +256,7 @@ impl DataManager {
let res = execute!( let res = execute!(
&conn, &conn,
"UPDATE users SET verified = $1 WHERE id = $2", "UPDATE users SET verified = $1 WHERE id = $2",
params![&(if x { 1 } else { 0 } as i32), &(id as i64)] params![&{ if x { 1 } else { 0 } }, &(id as i64)]
); );
if let Err(e) = res { if let Err(e) = res {
@ -327,7 +323,7 @@ impl DataManager {
let res = execute!( let res = execute!(
&conn, &conn,
"UPDATE users SET username = $1 WHERE id = $3", "UPDATE users SET username = $1 WHERE id = $2",
params![&to.as_str(), &(id as i64)] params![&to.as_str(), &(id as i64)]
); );
@ -414,7 +410,7 @@ impl DataManager {
return Err(Error::DatabaseError(e.to_string())); return Err(Error::DatabaseError(e.to_string()));
} }
self.cache_clear_user(&user).await; self.cache_clear_user(user).await;
Ok(()) Ok(())
} }

View file

@ -174,7 +174,7 @@ macro_rules! auto_method {
if !user.permissions.check(FinePermission::$permission) { if !user.permissions.check(FinePermission::$permission) {
return Err(Error::NotAllowed); return Err(Error::NotAllowed);
} else { } else {
self.create_audit_log_entry(crate::model::moderation::AuditLogEntry::new( self.create_audit_log_entry($crate::model::moderation::AuditLogEntry::new(
user.id, user.id,
format!("invoked `{}` with x value `{id}`", stringify!($name)), format!("invoked `{}` with x value `{id}`", stringify!($name)),
)) ))
@ -204,7 +204,7 @@ macro_rules! auto_method {
if !user.permissions.check(FinePermission::$permission) { if !user.permissions.check(FinePermission::$permission) {
return Err(Error::NotAllowed); return Err(Error::NotAllowed);
} else { } else {
self.create_audit_log_entry(crate::model::moderation::AuditLogEntry::new( self.create_audit_log_entry($crate::model::moderation::AuditLogEntry::new(
user.id, user.id,
format!("invoked `{}` with x value `{id}`", stringify!($name)), format!("invoked `{}` with x value `{id}`", stringify!($name)),
)) ))
@ -236,7 +236,7 @@ macro_rules! auto_method {
if !user.permissions.check(FinePermission::$permission) { if !user.permissions.check(FinePermission::$permission) {
return Err(Error::NotAllowed); return Err(Error::NotAllowed);
} else { } else {
self.create_audit_log_entry(crate::model::moderation::AuditLogEntry::new( self.create_audit_log_entry($crate::model::moderation::AuditLogEntry::new(
user.id, user.id,
format!("invoked `{}` with x value `{id}`", stringify!($name)), format!("invoked `{}` with x value `{id}`", stringify!($name)),
)) ))

View file

@ -224,9 +224,9 @@ impl DataManager {
&serde_json::to_string(&data.read_access).unwrap().as_str(), &serde_json::to_string(&data.read_access).unwrap().as_str(),
&serde_json::to_string(&data.write_access).unwrap().as_str(), &serde_json::to_string(&data.write_access).unwrap().as_str(),
&serde_json::to_string(&data.join_access).unwrap().as_str(), &serde_json::to_string(&data.join_access).unwrap().as_str(),
&(0 as i32), &0_i32,
&(0 as i32), &0_i32,
&(1 as i32) &1_i32
] ]
); );

View file

@ -21,7 +21,7 @@ pub struct DataManager(
impl DataManager { impl DataManager {
/// Obtain a connection to the staging database. /// Obtain a connection to the staging database.
pub(crate) async fn connect(&self) -> Result<Connection> { pub(crate) async fn connect(&self) -> Result<Connection> {
Ok(Connection::open(&self.0.database.name)?) Connection::open(&self.0.database.name)
} }
/// Create a new [`DataManager`] (and init database). /// Create a new [`DataManager`] (and init database).

View file

@ -50,7 +50,7 @@ impl DataManager {
) -> Result<Vec<(CommunityMembership, User)>> { ) -> Result<Vec<(CommunityMembership, User)>> {
let mut users: Vec<(CommunityMembership, User)> = Vec::new(); let mut users: Vec<(CommunityMembership, User)> = Vec::new();
for membership in list { for membership in list {
let owner = membership.owner.clone(); let owner = membership.owner;
users.push((membership, self.get_user_by_id(owner).await?)); users.push((membership, self.get_user_by_id(owner).await?));
} }
Ok(users) Ok(users)

View file

@ -21,11 +21,7 @@ impl DataManager {
title: get!(x->2(String)), title: get!(x->2(String)),
content: get!(x->3(String)), content: get!(x->3(String)),
owner: get!(x->4(i64)) as usize, owner: get!(x->4(i64)) as usize,
read: if get!(x->5(i32)) as i8 == 1 { read: get!(x->5(i32)) as i8 == 1,
true
} else {
false
},
} }
} }
@ -71,7 +67,7 @@ impl DataManager {
&data.title, &data.title,
&data.content, &data.content,
&(data.owner as i64), &(data.owner as i64),
&(if data.read { 1 } else { 0 } as i32) &{ if data.read { 1 } else { 0 } }
] ]
); );
@ -89,10 +85,8 @@ impl DataManager {
pub async fn delete_notification(&self, id: usize, user: &User) -> Result<()> { pub async fn delete_notification(&self, id: usize, user: &User) -> Result<()> {
let notification = self.get_notification_by_id(id).await?; let notification = self.get_notification_by_id(id).await?;
if user.id != notification.owner { if user.id != notification.owner && !user.permissions.check(FinePermission::MANAGE_NOTIFICATIONS) {
if !user.permissions.check(FinePermission::MANAGE_NOTIFICATIONS) { return Err(Error::NotAllowed);
return Err(Error::NotAllowed);
}
} }
let conn = match self.connect().await { let conn = match self.connect().await {
@ -127,10 +121,8 @@ impl DataManager {
let notifications = self.get_notifications_by_owner(user.id).await?; let notifications = self.get_notifications_by_owner(user.id).await?;
for notification in notifications { for notification in notifications {
if user.id != notification.owner { if user.id != notification.owner && !user.permissions.check(FinePermission::MANAGE_NOTIFICATIONS) {
if !user.permissions.check(FinePermission::MANAGE_NOTIFICATIONS) { return Err(Error::NotAllowed);
return Err(Error::NotAllowed);
}
} }
self.delete_notification(notification.id, user).await? self.delete_notification(notification.id, user).await?
@ -147,10 +139,8 @@ impl DataManager {
) -> Result<()> { ) -> Result<()> {
let y = self.get_notification_by_id(id).await?; let y = self.get_notification_by_id(id).await?;
if y.owner != user.id { if y.owner != user.id && !user.permissions.check(FinePermission::MANAGE_NOTIFICATIONS) {
if !user.permissions.check(FinePermission::MANAGE_NOTIFICATIONS) { return Err(Error::NotAllowed);
return Err(Error::NotAllowed);
}
} }
// ... // ...
@ -162,7 +152,7 @@ impl DataManager {
let res = execute!( let res = execute!(
&conn, &conn,
"UPDATE notifications SET read = $1 WHERE id = $2", "UPDATE notifications SET read = $1 WHERE id = $2",
params![&(if new_read { 1 } else { 0 } as i32), &(id as i64)] params![&{ if new_read { 1 } else { 0 } }, &(id as i64)]
); );
if let Err(e) = res { if let Err(e) = res {
@ -171,9 +161,9 @@ impl DataManager {
self.2.remove(format!("atto.notification:{}", id)).await; self.2.remove(format!("atto.notification:{}", id)).await;
if (y.read == true) && (new_read == false) { if (y.read) && (!new_read) {
self.incr_user_notifications(user.id).await?; self.incr_user_notifications(user.id).await?;
} else if (y.read == false) && (new_read == true) { } else if (!y.read) && (new_read) {
self.decr_user_notifications(user.id).await?; self.decr_user_notifications(user.id).await?;
} }

View file

@ -33,11 +33,7 @@ impl DataManager {
owner: get!(x->3(i64)) as usize, owner: get!(x->3(i64)) as usize,
community: get!(x->4(i64)) as usize, community: get!(x->4(i64)) as usize,
context: serde_json::from_str(&get!(x->5(String))).unwrap(), context: serde_json::from_str(&get!(x->5(String))).unwrap(),
replying_to: if let Some(id) = get!(x->6(Option<i64>)) { replying_to: get!(x->6(Option<i64>)).map(|id| id as usize),
Some(id as usize)
} else {
None
},
// likes // likes
likes: get!(x->7(i32)) as isize, likes: get!(x->7(i32)) as isize,
dislikes: get!(x->8(i32)) as isize, dislikes: get!(x->8(i32)) as isize,
@ -79,20 +75,52 @@ impl DataManager {
Ok(res.unwrap()) Ok(res.unwrap())
} }
/// Get the post the given post is reposting (if some).
pub async fn get_post_reposting(&self, post: &Post) -> Option<(User, Post)> {
if let Some(ref repost) = post.context.repost {
if let Some(reposting) = repost.reposting {
let mut x = match self.get_post_by_id(reposting).await {
Ok(p) => p,
Err(_) => return None,
};
x.mark_as_repost();
Some((
match self.get_user_by_id(x.owner).await {
Ok(ua) => ua,
Err(_) => return None,
},
x,
))
} else {
None
}
} else {
None
}
}
/// Complete a vector of just posts with their owner as well. /// Complete a vector of just posts with their owner as well.
pub async fn fill_posts(&self, posts: Vec<Post>) -> Result<Vec<(Post, User)>> { pub async fn fill_posts(
let mut out: Vec<(Post, User)> = Vec::new(); &self,
posts: Vec<Post>,
) -> Result<Vec<(Post, User, Option<(User, Post)>)>> {
let mut out: Vec<(Post, User, Option<(User, Post)>)> = Vec::new();
let mut users: HashMap<usize, User> = HashMap::new(); let mut users: HashMap<usize, User> = HashMap::new();
for post in posts { for post in posts {
let owner = post.owner.clone(); let owner = post.owner;
if let Some(user) = users.get(&owner) { if let Some(user) = users.get(&owner) {
out.push((post, user.clone())); out.push((
post.clone(),
user.clone(),
self.get_post_reposting(&post).await,
));
} else { } else {
let user = self.get_user_by_id(owner).await?; let user = self.get_user_by_id(owner).await?;
users.insert(owner, user.clone()); users.insert(owner, user.clone());
out.push((post, user)); out.push((post.clone(), user, self.get_post_reposting(&post).await));
} }
} }
@ -103,22 +131,62 @@ impl DataManager {
pub async fn fill_posts_with_community( pub async fn fill_posts_with_community(
&self, &self,
posts: Vec<Post>, posts: Vec<Post>,
) -> Result<Vec<(Post, User, Community)>> { user_id: usize,
let mut out: Vec<(Post, User, Community)> = Vec::new(); ) -> Result<Vec<(Post, User, Community, Option<(User, Post)>)>> {
let mut out: Vec<(Post, User, Community, Option<(User, Post)>)> = Vec::new();
let mut seen_before: HashMap<(usize, usize), (User, Community)> = HashMap::new(); let mut seen_before: HashMap<(usize, usize), (User, Community)> = HashMap::new();
let mut seen_user_follow_statuses: HashMap<(usize, usize), bool> = HashMap::new();
for post in posts { for post in posts {
let owner = post.owner.clone(); let owner = post.owner;
let community = post.community.clone(); let community = post.community;
if let Some((user, community)) = seen_before.get(&(owner, community)) { if let Some((user, community)) = seen_before.get(&(owner, community)) {
out.push((post, user.clone(), community.to_owned())); out.push((
post.clone(),
user.clone(),
community.to_owned(),
self.get_post_reposting(&post).await,
));
} else { } else {
let user = self.get_user_by_id(owner).await?; let user = self.get_user_by_id(owner).await?;
let community = self.get_community_by_id(community).await?;
// check relationship
if user.settings.private_profile {
if user_id == 0 {
continue;
}
if let Some(is_following) = seen_user_follow_statuses.get(&(user.id, user_id)) {
if !is_following {
// post owner is not following us
continue;
}
} else {
if self
.get_userfollow_by_initiator_receiver(user.id, user_id)
.await
.is_err()
{
// post owner is not following us
seen_user_follow_statuses.insert((user.id, user_id), false);
continue;
}
seen_user_follow_statuses.insert((user.id, user_id), true);
}
}
// ...
let community = self.get_community_by_id(community).await?;
seen_before.insert((owner, community.id), (user.clone(), community.clone())); seen_before.insert((owner, community.id), (user.clone(), community.clone()));
out.push((post, user, community)); out.push((
post.clone(),
user,
community,
self.get_post_reposting(&post).await,
));
} }
} }
@ -357,25 +425,13 @@ impl DataManager {
/// Check if the given `uid` can post in the given `community`. /// Check if the given `uid` can post in the given `community`.
pub async fn check_can_post(&self, community: &Community, uid: usize) -> bool { pub async fn check_can_post(&self, community: &Community, uid: usize) -> bool {
match community.write_access { match community.write_access {
CommunityWriteAccess::Owner => { CommunityWriteAccess::Owner => uid == community.owner,
if uid != community.owner {
false
} else {
true
}
}
CommunityWriteAccess::Joined => { CommunityWriteAccess::Joined => {
match self match self
.get_membership_by_owner_community(uid, community.id) .get_membership_by_owner_community(uid, community.id)
.await .await
{ {
Ok(m) => { Ok(m) => !(!m.role.check_member()),
if !m.role.check_member() {
false
} else {
true
}
}
Err(_) => false, Err(_) => false,
} }
} }
@ -388,11 +444,19 @@ impl DataManager {
/// # Arguments /// # Arguments
/// * `data` - a mock [`JournalEntry`] object to insert /// * `data` - a mock [`JournalEntry`] object to insert
pub async fn create_post(&self, mut data: Post) -> Result<usize> { pub async fn create_post(&self, mut data: Post) -> Result<usize> {
// check values // check values (if this isn't reposting something else)
if data.content.len() < 2 { let is_reposting = if let Some(ref repost) = data.context.repost {
return Err(Error::DataTooShort("content".to_string())); repost.reposting.is_some()
} else if data.content.len() > 4096 { } else {
return Err(Error::DataTooLong("username".to_string())); false
};
if !is_reposting {
if data.content.len() < 2 {
return Err(Error::DataTooShort("content".to_string()));
} else if data.content.len() > 4096 {
return Err(Error::DataTooLong("content".to_string()));
}
} }
// check permission in community // check permission in community
@ -408,10 +472,37 @@ impl DataManager {
// mirror nsfw state // mirror nsfw state
data.context.is_nsfw = community.context.is_nsfw; data.context.is_nsfw = community.context.is_nsfw;
// check if we're blocked // check if we're reposting a post
if let Some(replying_to) = data.replying_to { let reposting = if let Some(ref repost) = data.context.repost {
if let Some(id) = repost.reposting {
Some(self.get_post_by_id(id).await?)
} else {
None
}
} else {
None
};
if let Some(ref rt) = reposting {
data.context.reposts_enabled = false; // cannot repost reposts
// make sure we aren't trying to repost a repost
if if let Some(ref repost) = rt.context.repost {
!(!repost.is_repost)
} else {
false
} {
return Err(Error::MiscError("Cannot repost a repost".to_string()));
}
// ...
if !rt.context.reposts_enabled {
return Err(Error::MiscError("Post has reposts disabled".to_string()));
}
// check blocked status
if let Ok(_) = self if let Ok(_) = self
.get_userblock_by_initiator_receiver(replying_to, data.owner) .get_userblock_by_initiator_receiver(rt.owner, data.owner)
.await .await
{ {
return Err(Error::NotAllowed); return Err(Error::NotAllowed);
@ -429,6 +520,14 @@ impl DataManager {
if !rt.context.comments_enabled { if !rt.context.comments_enabled {
return Err(Error::MiscError("Post has comments disabled".to_string())); return Err(Error::MiscError("Post has comments disabled".to_string()));
} }
// check blocked status
if let Ok(_) = self
.get_userblock_by_initiator_receiver(rt.owner, data.owner)
.await
{
return Err(Error::NotAllowed);
}
} }
// send mention notifications // send mention notifications
@ -480,11 +579,11 @@ impl DataManager {
&if replying_to_id != "0" { &if replying_to_id != "0" {
replying_to_id.parse::<i64>().unwrap() replying_to_id.parse::<i64>().unwrap()
} else { } else {
0 as i64 0_i64
}, },
&(0 as i32), &0_i32,
&(0 as i32), &0_i32,
&(0 as i32) &0_i32
] ]
); );
@ -509,7 +608,7 @@ impl DataManager {
)) ))
.await?; .await?;
if rt.context.comments_enabled == false { if !rt.context.comments_enabled {
return Err(Error::NotAllowed); return Err(Error::NotAllowed);
} }
} }
@ -564,8 +663,14 @@ impl DataManager {
Ok(()) Ok(())
} }
pub async fn update_post_context(&self, id: usize, user: User, x: PostContext) -> Result<()> { pub async fn update_post_context(
&self,
id: usize,
user: User,
mut x: PostContext,
) -> Result<()> {
let y = self.get_post_by_id(id).await?; let y = self.get_post_by_id(id).await?;
x.repost = y.context.repost; // cannot change repost settings at all
let user_membership = self let user_membership = self
.get_membership_by_owner_community(user.id, y.community) .get_membership_by_owner_community(user.id, y.community)
@ -588,19 +693,19 @@ impl DataManager {
} }
// check if we can manage pins // check if we can manage pins
if x.is_pinned != y.context.is_pinned { if x.is_pinned != y.context.is_pinned
if !user_membership.role.check(CommunityPermission::MANAGE_PINS) { && !user_membership.role.check(CommunityPermission::MANAGE_PINS)
// lacking this permission is overtaken by having the MANAGE_POSTS {
// global permission // lacking this permission is overtaken by having the MANAGE_POSTS
if !user.permissions.check(FinePermission::MANAGE_POSTS) { // global permission
return Err(Error::NotAllowed); if !user.permissions.check(FinePermission::MANAGE_POSTS) {
} else { return Err(Error::NotAllowed);
self.create_audit_log_entry(AuditLogEntry::new( } else {
user.id, self.create_audit_log_entry(AuditLogEntry::new(
format!("invoked `update_post_context(pinned)` with x value `{id}`"), user.id,
)) format!("invoked `update_post_context(pinned)` with x value `{id}`"),
.await? ))
} .await?
} }
} }

View file

@ -26,11 +26,7 @@ impl DataManager {
owner: get!(x->2(i64)) as usize, owner: get!(x->2(i64)) as usize,
asset: get!(x->3(i64)) as usize, asset: get!(x->3(i64)) as usize,
asset_type: serde_json::from_str(&get!(x->4(String))).unwrap(), asset_type: serde_json::from_str(&get!(x->4(String))).unwrap(),
is_like: if get!(x->5(i32)) as i8 == 1 { is_like: get!(x->5(i32)) as i8 == 1,
true
} else {
false
},
} }
} }
@ -80,7 +76,7 @@ impl DataManager {
&(data.owner as i64), &(data.owner as i64),
&(data.asset as i64), &(data.asset as i64),
&serde_json::to_string(&data.asset_type).unwrap().as_str(), &serde_json::to_string(&data.asset_type).unwrap().as_str(),
&(if data.is_like { 1 } else { 0 } as i32) &{ if data.is_like { 1 } else { 0 } }
] ]
); );
@ -103,7 +99,7 @@ impl DataManager {
let community = self.get_community_by_id_no_void(data.asset).await.unwrap(); let community = self.get_community_by_id_no_void(data.asset).await.unwrap();
if community.owner != user.id { if community.owner != user.id {
if let Err(e) = self self
.create_notification(Notification::new( .create_notification(Notification::new(
"Your community has received a like!".to_string(), "Your community has received a like!".to_string(),
format!( format!(
@ -112,10 +108,7 @@ impl DataManager {
), ),
community.owner, community.owner,
)) ))
.await .await?
{
return Err(e);
}
} }
} }
} }
@ -132,19 +125,16 @@ impl DataManager {
let post = self.get_post_by_id(data.asset).await.unwrap(); let post = self.get_post_by_id(data.asset).await.unwrap();
if post.owner != user.id { if post.owner != user.id {
if let Err(e) = self self
.create_notification(Notification::new( .create_notification(Notification::new(
"Your post has received a like!".to_string(), "Your post has received a like!".to_string(),
format!( format!(
"[@{}](/api/v1/auth/user/find/{}) has liked your post!", "[@{}](/api/v1/auth/user/find/{}) has liked your [post](/post/{})!",
user.username, user.id user.username, user.id, data.asset
), ),
post.owner, post.owner,
)) ))
.await .await?
{
return Err(e);
}
} }
} }
} }
@ -160,10 +150,8 @@ impl DataManager {
pub async fn delete_reaction(&self, id: usize, user: &User) -> Result<()> { pub async fn delete_reaction(&self, id: usize, user: &User) -> Result<()> {
let reaction = self.get_reaction_by_id(id).await?; let reaction = self.get_reaction_by_id(id).await?;
if user.id != reaction.owner { if user.id != reaction.owner && !user.permissions.check(FinePermission::MANAGE_REACTIONS) {
if !user.permissions.check(FinePermission::MANAGE_REACTIONS) { return Err(Error::NotAllowed);
return Err(Error::NotAllowed);
}
} }
let conn = match self.connect().await { let conn = match self.connect().await {
@ -186,26 +174,22 @@ impl DataManager {
// decr corresponding // decr corresponding
match reaction.asset_type { match reaction.asset_type {
AssetType::Community => { AssetType::Community => {
if let Err(e) = { {
if reaction.is_like { if reaction.is_like {
self.decr_community_likes(reaction.asset).await self.decr_community_likes(reaction.asset).await
} else { } else {
self.decr_community_dislikes(reaction.asset).await self.decr_community_dislikes(reaction.asset).await
} }
} { }?
return Err(e);
}
} }
AssetType::Post => { AssetType::Post => {
if let Err(e) = { {
if reaction.is_like { if reaction.is_like {
self.decr_post_likes(reaction.asset).await self.decr_post_likes(reaction.asset).await
} else { } else {
self.decr_post_dislikes(reaction.asset).await self.decr_post_dislikes(reaction.asset).await
} }
} { }?
return Err(e);
}
} }
AssetType::User => { AssetType::User => {
return Err(Error::NotAllowed); return Err(Error::NotAllowed);

View file

@ -193,7 +193,7 @@ impl DataManager {
let mut out: Vec<(UserFollow, User)> = Vec::new(); let mut out: Vec<(UserFollow, User)> = Vec::new();
for userfollow in userfollows { for userfollow in userfollows {
let receiver = userfollow.receiver.clone(); let receiver = userfollow.receiver;
out.push((userfollow, self.get_user_by_id(receiver).await?)); out.push((userfollow, self.get_user_by_id(receiver).await?));
} }
@ -208,7 +208,7 @@ impl DataManager {
let mut out: Vec<(UserFollow, User)> = Vec::new(); let mut out: Vec<(UserFollow, User)> = Vec::new();
for userfollow in userfollows { for userfollow in userfollows {
let initiator = userfollow.initiator.clone(); let initiator = userfollow.initiator;
out.push((userfollow, self.get_user_by_id(initiator).await?)); out.push((userfollow, self.get_user_by_id(initiator).await?));
} }
@ -254,10 +254,8 @@ impl DataManager {
pub async fn delete_userfollow(&self, id: usize, user: &User) -> Result<()> { pub async fn delete_userfollow(&self, id: usize, user: &User) -> Result<()> {
let follow = self.get_userfollow_by_id(id).await?; let follow = self.get_userfollow_by_id(id).await?;
if (user.id != follow.initiator) && (user.id != follow.receiver) { if (user.id != follow.initiator) && (user.id != follow.receiver) && !user.permissions.check(FinePermission::MANAGE_FOLLOWS) {
if !user.permissions.check(FinePermission::MANAGE_FOLLOWS) { return Err(Error::NotAllowed);
return Err(Error::NotAllowed);
}
} }
let conn = match self.connect().await { let conn = match self.connect().await {

View file

@ -47,6 +47,7 @@ impl Default for ThemePreference {
} }
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
#[derive(Default)]
pub struct UserSettings { pub struct UserSettings {
#[serde(default)] #[serde(default)]
pub policy_consent: bool, pub policy_consent: bool,
@ -72,23 +73,6 @@ pub struct UserSettings {
pub disable_other_themes: bool, pub disable_other_themes: bool,
} }
impl Default for UserSettings {
fn default() -> Self {
Self {
policy_consent: false,
display_name: String::new(),
biography: String::new(),
private_profile: false,
private_communities: false,
theme_preference: ThemePreference::default(),
private_last_seen: false,
theme_hue: String::new(),
theme_sat: String::new(),
theme_lit: String::new(),
disable_other_themes: false,
}
}
}
impl Default for User { impl Default for User {
fn default() -> Self { fn default() -> Self {
@ -212,7 +196,7 @@ impl User {
return None; return None;
} }
match TOTP::new( TOTP::new(
totp_rs::Algorithm::SHA1, totp_rs::Algorithm::SHA1,
6, 6,
1, 1,
@ -220,10 +204,7 @@ impl User {
self.totp.as_bytes().to_owned(), self.totp.as_bytes().to_owned(),
Some(issuer.unwrap_or("tetratto!".to_string())), Some(issuer.unwrap_or("tetratto!".to_string())),
self.username.clone(), self.username.clone(),
) { ).ok()
Ok(t) => Some(t),
Err(_) => None,
}
} }
} }

View file

@ -70,7 +70,7 @@ impl Community {
} }
} }
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct CommunityContext { pub struct CommunityContext {
#[serde(default)] #[serde(default)]
pub display_name: String, pub display_name: String,
@ -80,16 +80,6 @@ pub struct CommunityContext {
pub is_nsfw: bool, pub is_nsfw: bool,
} }
impl Default for CommunityContext {
fn default() -> Self {
Self {
display_name: String::new(),
description: String::new(),
is_nsfw: false,
}
}
}
/// Who can read a [`Community`]. /// Who can read a [`Community`].
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum CommunityReadAccess { pub enum CommunityReadAccess {
@ -166,7 +156,7 @@ impl CommunityMembership {
} }
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PostContext { pub struct PostContext {
#[serde(default = "default_comments_enabled")] #[serde(default = "default_comments_enabled")]
pub comments_enabled: bool, pub comments_enabled: bool,
@ -178,25 +168,47 @@ pub struct PostContext {
pub edited: usize, pub edited: usize,
#[serde(default)] #[serde(default)]
pub is_nsfw: bool, pub is_nsfw: bool,
#[serde(default)]
pub repost: Option<RepostContext>,
#[serde(default = "default_reposts_enabled")]
pub reposts_enabled: bool,
} }
fn default_comments_enabled() -> bool { fn default_comments_enabled() -> bool {
true true
} }
fn default_reposts_enabled() -> bool {
true
}
impl Default for PostContext { impl Default for PostContext {
fn default() -> Self { fn default() -> Self {
Self { Self {
comments_enabled: default_comments_enabled(), comments_enabled: default_comments_enabled(),
reposts_enabled: true,
is_pinned: false, is_pinned: false,
is_profile_pinned: false, is_profile_pinned: false,
edited: 0, edited: 0,
is_nsfw: false, is_nsfw: false,
repost: None,
} }
} }
} }
#[derive(Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RepostContext {
/// Should be `false` is `repost_of` is `Some`.
///
/// Declares the post to be a repost of another post.
pub is_repost: bool,
/// Should be `None` if `is_repost` is true.
///
/// Sets the ID of the other post to load.
pub reposting: Option<usize>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Post { pub struct Post {
pub id: usize, pub id: usize,
pub created: usize, pub created: usize,
@ -238,4 +250,24 @@ impl Post {
comment_count: 0, comment_count: 0,
} }
} }
/// Create a new [`Post`] (as a repost of the given `post_id`).
pub fn repost(content: String, community: usize, owner: usize, post_id: usize) -> Self {
let mut post = Self::new(content, community, None, owner);
post.context.repost = Some(RepostContext {
is_repost: false,
reposting: Some(post_id),
});
post
}
/// Make the given post a reposted post.
pub fn mark_as_repost(&mut self) {
self.context.repost = Some(RepostContext {
is_repost: true,
reposting: None,
});
}
} }

View file

@ -32,7 +32,7 @@ impl Serialize for CommunityPermission {
} }
struct CommunityPermissionVisitor; struct CommunityPermissionVisitor;
impl<'de> Visitor<'de> for CommunityPermissionVisitor { impl Visitor<'_> for CommunityPermissionVisitor {
type Value = CommunityPermission; type Value = CommunityPermission;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {

View file

@ -54,14 +54,14 @@ impl ToString for Error {
} }
} }
impl<T> Into<ApiReturn<T>> for Error impl<T> From<Error> for ApiReturn<T>
where where
T: Default + Serialize, T: Default + Serialize,
{ {
fn into(self) -> ApiReturn<T> { fn from(val: Error) -> Self {
ApiReturn { ApiReturn {
ok: false, ok: false,
message: self.to_string(), message: val.to_string(),
payload: T::default(), payload: T::default(),
} }
} }

View file

@ -43,7 +43,7 @@ impl Serialize for FinePermission {
} }
struct FinePermissionVisitor; struct FinePermissionVisitor;
impl<'de> Visitor<'de> for FinePermissionVisitor { impl Visitor<'_> for FinePermissionVisitor {
type Value = FinePermission; type Value = FinePermission;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {

View file

@ -1,6 +1,6 @@
[package] [package]
name = "tetratto-l10n" name = "tetratto-l10n"
version = "1.0.1" version = "1.0.2"
edition = "2024" edition = "2024"
authors.workspace = true authors.workspace = true
repository.workspace = true repository.workspace = true

View file

@ -1,6 +1,6 @@
[package] [package]
name = "tetratto-shared" name = "tetratto-shared"
version = "1.0.1" version = "1.0.2"
edition = "2024" edition = "2024"
authors.workspace = true authors.workspace = true
repository.workspace = true repository.workspace = true