add: pinned posts

This commit is contained in:
trisua 2025-04-03 12:43:36 -04:00
parent e52733b00c
commit eea3d08e1f
10 changed files with 324 additions and 55 deletions

View file

@ -70,6 +70,7 @@ version = "1.0.0"
"communities:label.delete_community" = "Delete community"
"communities:label.change_title" = "Change title"
"communities:label.new_title" = "New title"
"communities:label.pinned" = "Pinned"
"notifs:action.mark_as_read" = "Mark as read"
"notifs:action.mark_as_unread" = "Mark as unread"

View file

@ -31,6 +31,20 @@
</button>
</form>
</div>
{% endif %} {% if pinned|length != 0 %}
<div class="card-nest">
<div class="card small flex gap-2 items-center">
{{ icon "pin" }}
<span>{{ text "communities:label.pinned" }}</span>
</div>
<div class="card flex flex-col gap-4">
<!-- prettier-ignore -->
{% for post in pinned %}
{{ components::post(post=post[0], owner=post[1], secondary=true, show_community=false, can_manage_post=can_manage_posts) }}
{% endfor %}
</div>
</div>
{% endif %}
<div class="card-nest">
@ -42,7 +56,7 @@
<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) }}
{{ components::post(post=post[0], owner=post[1], secondary=true, show_community=false, can_manage_post=can_manage_posts) }}
{% endfor %}
{{ components::pagination(page=page, items=feed|length) }}

View file

@ -8,7 +8,8 @@
<span>{{ text "communities:action.continue_thread" }}</span>
</a>
{% endif %} {{ components::post(post=post, owner=owner, community=community,
show_community=true) }} {% if user %}
show_community=true, can_manage_post=can_manage_posts) }} {% if user and
post.context.comments_enabled %}
<div class="card-nest">
<div class="card small">
<b>{{ text "communities:label.create_reply" }}</b>
@ -38,9 +39,91 @@
</button>
</form>
</div>
{% endif %} {% if user and user.id == post.owner or can_manage_posts %}
<div class="pillmenu">
<a href="#/replies" data-tab-button="replies" class="active">
{{ icon "newspaper" }}
<span>{{ text "communities:label.replies" }}</span>
</a>
<a href="#/configure" data-tab-button="configure">
{{ icon "settings" }}
<span>{{ text "communities:action.configure" }}</span>
</a>
</div>
<div class="flex flex-col gap-2 hidden" data-tab="configure">
<div class="card-nest w-full">
<div class="card small flex items-center gap-2">
{{ icon "settings" }}
<span>{{ text "communities:action.configure" }}</span>
</div>
<div
class="card tertiary flex flex-col gap-4"
id="post_context"
></div>
</div>
<button onclick="save_context()">
{{ icon "check" }}
<span>{{ text "general:action.save" }}</span>
</button>
<script>
setTimeout(() => {
const ui = ns("ui");
const element = document.getElementById("post_context");
const settings = JSON.parse("{{ post_context_serde|safe }}");
globalThis.save_context = () => {
fetch("/api/v1/posts/{{ post.id }}/context", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
context: settings,
}),
})
.then((res) => res.json())
.then((res) => {
trigger("atto::toast", [
res.ok ? "success" : "error",
res.message,
]);
});
};
ui.refresh_container(element, []);
const can_manage_pins = "{{ can_manage_pins }}" === "true";
const settings_fields = [
[
[
"comments_enabled",
"Allow people to comment on your post",
],
"{{ post.context.comments_enabled }}",
"checkbox",
],
];
if (can_manage_pins) {
settings_fields.push([
["is_pinned", "Pinned to community wall"],
"{{ post.context.is_pinned }}",
"checkbox",
]);
}
ui.generate_settings_ui(element, settings_fields, settings);
}, 250);
</script>
</div>
{% endif %}
<div class="card-nest w-full">
<div class="card-nest w-full" data-tab="replies">
<div class="card small flex items-center gap-2">
{{ icon "newspaper" }}
<span>{{ text "communities:label.replies" }}</span>

View file

@ -346,7 +346,7 @@
role: (new_role) => {
return update_user_role(
e.target.uid.value,
user_role,
new_role,
);
},
},

View file

@ -105,7 +105,8 @@ community %}
{% endif %}
</div>
{%- endmacro %} {% macro post(post, owner, secondary=false, community=false,
show_community=true) -%} {% if community and show_community %}
show_community=true, can_manage_post=false) -%} {% if community and
show_community %}
<div class="card-nest">
<div class="card small">
<a
@ -115,6 +116,8 @@ show_community=true) -%} {% if community and show_community %}
{{ components::community_avatar(id=post.community,
community=community) }}
<b>{{ community.title }}</b>
{% if post.context.is_pinned %} {{ icon "pin" }} {% endif %}
</a>
</div>
{% endif %}
@ -197,7 +200,7 @@ show_community=true) -%} {% if community and show_community %}
<span>{{ text "general:action.report" }}</span>
</button>
{% endif %} {% if (user.id == post.owner) or is_helper
%}
or can_manage_post %}
<b class="title">{{ text "general:action.manage" }}</b>
<button
class="red"

View file

@ -736,12 +736,17 @@ media_theme_pref();
const self = reg_ns("ui");
self.define("refresh_container", (_, element, keep) => {
if (keep.length === 0) {
element.innerHTML = "";
return;
}
for (const child of element.children) {
if (keep.includes(child.getAttribute("ui_ident"))) {
continue;
}
child.remove();
child.outerHTML = "";
}
});

View file

@ -18,6 +18,7 @@ use tetratto_core::model::{
macro_rules! check_permissions {
($community:ident, $jar:ident, $data:ident, $user:ident) => {{
let mut is_member: bool = false;
let mut can_manage_pins: bool = false;
if let Some(ref ua) = $user {
if let Ok(membership) = $data
@ -32,18 +33,24 @@ macro_rules! check_permissions {
} else if membership.role.check_member() {
is_member = true;
}
if membership.role.check(
tetratto_core::model::communities_permissions::CommunityPermission::MANAGE_PINS,
) {
can_manage_pins = true;
}
}
}
match $community.read_access {
CommunityReadAccess::Joined => {
if !is_member {
false
(false, can_manage_pins)
} else {
true
(true, can_manage_pins)
}
}
_ => true,
_ => (true, can_manage_pins),
}
}};
}
@ -87,7 +94,13 @@ macro_rules! community_context_bools {
false
};
(is_owner, is_joined, is_pending, can_post)
let can_manage_posts = if let Some(ref membership) = membership {
membership.role.check(CommunityPermission::MANAGE_POSTS)
} else {
false
};
(is_owner, is_joined, is_pending, can_post, can_manage_posts)
}};
}
@ -141,6 +154,7 @@ pub fn community_context(
is_pending: bool,
can_post: bool,
can_read: bool,
can_manage_posts: bool,
) {
context.insert("community", &community);
context.insert("is_owner", &is_owner);
@ -148,6 +162,7 @@ pub fn community_context(
context.insert("is_pending", &is_pending);
context.insert("can_post", &can_post);
context.insert("can_read", &can_read);
context.insert("can_manage_posts", &can_manage_posts);
}
/// `/community/{title}`
@ -179,7 +194,7 @@ pub async fn feed_request(
}
// check permissions
let can_read = check_permissions!(community, jar, data, user);
let (can_read, _) = check_permissions!(community, jar, data, user);
// ...
let feed = match data
@ -194,14 +209,23 @@ pub async fn feed_request(
Err(e) => return Err(Html(render_error(e, &jar, &data, &user).await)),
};
let pinned = match data.0.get_pinned_posts_by_community(community.id).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, is_joined, is_pending, can_post) =
let (is_owner, is_joined, is_pending, can_post, can_manage_posts) =
community_context_bools!(data, user, community);
context.insert("feed", &feed);
context.insert("pinned", &pinned);
context.insert("page", &props.page);
community_context(
&mut context,
@ -211,6 +235,7 @@ pub async fn feed_request(
is_pending,
can_post,
can_read,
can_manage_posts,
);
// return
@ -287,7 +312,7 @@ pub async fn post_request(
};
// check permissions
let can_read = check_permissions!(community, jar, data, user);
let (can_read, can_manage_pins) = check_permissions!(community, jar, data, user);
// ...
let feed = match data.0.get_post_comments(post.id, 12, props.page).await {
@ -302,7 +327,7 @@ pub async fn post_request(
let lang = get_lang!(jar, data.0);
let mut context = initial_context(&data.0.0, lang, &user).await;
let (is_owner, is_joined, is_pending, can_post) =
let (is_owner, is_joined, is_pending, can_post, can_manage_posts) =
community_context_bools!(data, user, community);
context.insert("post", &post);
@ -316,6 +341,14 @@ pub async fn post_request(
.await
.unwrap_or(User::deleted()),
);
context.insert(
"post_context_serde",
&serde_json::to_string(&post.context)
.unwrap()
.replace("\"", "\\\""),
);
context.insert("can_manage_pins", &can_manage_pins);
community_context(
&mut context,
&community,
@ -324,6 +357,7 @@ pub async fn post_request(
is_pending,
can_post,
can_read,
can_manage_posts,
);
// return

View file

@ -3,6 +3,8 @@ use std::collections::HashMap;
use super::*;
use crate::cache::Cache;
use crate::model::auth::Notification;
use crate::model::communities_permissions::CommunityPermission;
use crate::model::moderation::AuditLogEntry;
use crate::model::{
Error, Result,
auth::User,
@ -84,9 +86,17 @@ impl DataManager {
pub async fn fill_posts(&self, posts: Vec<Post>) -> Result<Vec<(Post, User)>> {
let mut out: Vec<(Post, User)> = Vec::new();
let mut users: HashMap<usize, User> = HashMap::new();
for post in posts {
let owner = post.owner.clone();
out.push((post, self.get_user_by_id(owner).await?));
if let Some(user) = users.get(&owner) {
out.push((post, user.clone()));
} else {
let user = self.get_user_by_id(owner).await?;
users.insert(owner, user.clone());
out.push((post, user));
}
}
Ok(out)
@ -99,14 +109,20 @@ impl DataManager {
) -> Result<Vec<(Post, User, Community)>> {
let mut out: Vec<(Post, User, Community)> = Vec::new();
let mut seen_before: HashMap<(usize, usize), (User, Community)> = HashMap::new();
for post in posts {
let owner = post.owner.clone();
let community = post.community.clone();
out.push((
post,
self.get_user_by_id(owner).await?,
self.get_community_by_id(community).await?,
));
if let Some((user, community)) = seen_before.get(&(owner, community)) {
out.push((post, user.clone(), community.to_owned()));
} else {
let user = self.get_user_by_id(owner).await?;
let community = self.get_community_by_id(community).await?;
seen_before.insert((owner, community.id), (user.clone(), community.clone()));
out.push((post, user, community));
}
}
Ok(out)
@ -182,6 +198,30 @@ impl DataManager {
Ok(res.unwrap())
}
/// Get all pinned posts from the given community (from most recent).
///
/// # Arguments
/// * `id` - the ID of the community the requested posts belong to
pub async fn get_pinned_posts_by_community(&self, id: usize) -> Result<Vec<Post>> {
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_rows!(
&conn,
"SELECT * FROM posts WHERE community = $1 AND context LIKE '%\"is_pinned\":true%' ORDER BY created DESC",
&[&(id as isize),],
|x| { Self::get_post_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("post".to_string()));
}
Ok(res.unwrap())
}
/// Get posts from all communities, sorted by likes.
///
/// # Arguments
@ -315,6 +355,19 @@ impl DataManager {
}
}
// check if the post we're replying to allows commments
let replying_to = if let Some(id) = data.replying_to {
Some(self.get_post_by_id(id).await?)
} else {
None
};
if let Some(ref rt) = replying_to {
if !rt.context.comments_enabled {
return Err(Error::MiscError("Post has comments disabled".to_string()));
}
}
// send mention notifications
let mut already_notified: HashMap<String, User> = HashMap::new();
for username in User::parse_mentions(&data.content) {
@ -343,31 +396,6 @@ impl DataManager {
);
}
// incr comment count
if let Some(id) = data.replying_to {
self.incr_post_comments(id).await.unwrap();
// send notification
let rt = self.get_post_by_id(id).await?;
if data.owner != rt.owner {
let owner = self.get_user_by_id(rt.owner).await?;
self.create_notification(Notification::new(
"Your post has received a new comment!".to_string(),
format!(
"[@{}](/api/v1/auth/profile/find/{}) has commented on your [post](/post/{}).",
owner.username, owner.id, rt.id
),
rt.owner,
))
.await?;
if rt.context.comments_enabled == false {
return Err(Error::NotAllowed);
}
}
}
// ...
let conn = match self.connect().await {
Ok(c) => c,
@ -401,6 +429,29 @@ impl DataManager {
return Err(Error::DatabaseError(e.to_string()));
}
// incr comment count and send notification
if let Some(rt) = replying_to {
self.incr_post_comments(rt.id).await.unwrap();
// send notification
if data.owner != rt.owner {
let owner = self.get_user_by_id(rt.owner).await?;
self.create_notification(Notification::new(
"Your post has received a new comment!".to_string(),
format!(
"[@{}](/api/v1/auth/profile/find/{}) has commented on your [post](/post/{}).",
owner.username, owner.id, rt.id
),
rt.owner,
))
.await?;
if rt.context.comments_enabled == false {
return Err(Error::NotAllowed);
}
}
}
// return
Ok(data.id)
}
@ -408,11 +459,19 @@ impl DataManager {
pub async fn delete_post(&self, id: usize, user: User) -> Result<()> {
let y = self.get_post_by_id(id).await?;
if user.id != y.owner {
let user_membership = self
.get_membership_by_owner_community(user.id, y.community)
.await?;
if (user.id != y.owner)
&& !user_membership
.role
.check(CommunityPermission::MANAGE_POSTS)
{
if !user.permissions.check(FinePermission::MANAGE_POSTS) {
return Err(Error::NotAllowed);
} else {
self.create_audit_log_entry(crate::model::moderation::AuditLogEntry::new(
self.create_audit_log_entry(AuditLogEntry::new(
user.id,
format!("invoked `delete_post` with x value `{id}`"),
))
@ -442,8 +501,69 @@ impl DataManager {
Ok(())
}
pub async fn update_post_context(&self, id: usize, user: User, x: PostContext) -> Result<()> {
let y = self.get_post_by_id(id).await?;
let user_membership = self
.get_membership_by_owner_community(user.id, y.community)
.await?;
if (user.id != y.owner)
&& !user_membership
.role
.check(CommunityPermission::MANAGE_POSTS)
{
if !user.permissions.check(FinePermission::MANAGE_POSTS) {
return Err(Error::NotAllowed);
} else {
self.create_audit_log_entry(AuditLogEntry::new(
user.id,
format!("invoked `update_post_context` with x value `{id}`"),
))
.await?
}
}
// check if we can manage pins
if x.is_pinned != y.context.is_pinned {
if !user_membership.role.check(CommunityPermission::MANAGE_PINS) {
// lacking this permission is overtaken by having the MANAGE_POSTS
// global permission
if !user.permissions.check(FinePermission::MANAGE_POSTS) {
return Err(Error::NotAllowed);
} else {
self.create_audit_log_entry(AuditLogEntry::new(
user.id,
format!("invoked `update_post_context(pinned)` with x value `{id}`"),
))
.await?
}
}
}
// ...
let conn = match self.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"UPDATE posts SET context = $1 WHERE id = $2",
&[&serde_json::to_string(&x).unwrap(), &id.to_string()]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.2.remove(format!("atto.post:{}", id)).await;
// return
Ok(())
}
auto_method!(update_post_content(String)@get_post_by_id:MANAGE_POSTS -> "UPDATE posts SET content = $1 WHERE id = $2" --cache-key-tmpl="atto.post:{}");
auto_method!(update_post_context(PostContext)@get_post_by_id:MANAGE_POSTS -> "UPDATE posts SET context = $1 WHERE id = $2" --serde --cache-key-tmpl="atto.post:{}");
auto_method!(incr_post_likes() -> "UPDATE posts SET likes = likes + 1 WHERE id = $1" --cache-key-tmpl="atto.post:{}" --incr);
auto_method!(incr_post_dislikes() -> "UPDATE posts SET dislikes = dislikes + 1 WHERE id = $1" --cache-key-tmpl="atto.post:{}" --incr);

View file

@ -3,7 +3,7 @@ use tetratto_shared::{snow::AlmostSnowflake, unix_epoch_timestamp};
use super::communities_permissions::CommunityPermission;
#[derive(Serialize, Deserialize)]
#[derive(Clone, Serialize, Deserialize)]
pub struct Community {
pub id: usize,
pub created: usize,
@ -70,7 +70,7 @@ impl Community {
}
}
#[derive(Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CommunityContext {
pub display_name: String,
pub description: String,
@ -86,7 +86,7 @@ impl Default for CommunityContext {
}
/// Who can read a [`Community`].
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum CommunityReadAccess {
/// Everybody can view the community.
Everybody,
@ -101,7 +101,7 @@ impl Default for CommunityReadAccess {
}
/// Who can write to a [`Community`].
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum CommunityWriteAccess {
/// Everybody.
Everybody,
@ -120,7 +120,7 @@ impl Default for CommunityWriteAccess {
}
/// Who can join a [`Community`].
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum CommunityJoinAccess {
/// Joins are closed. Nobody can join the community.
Nobody,
@ -163,13 +163,21 @@ impl CommunityMembership {
#[derive(Debug, Serialize, Deserialize)]
pub struct PostContext {
#[serde(default = "default_comments_enabled")]
pub comments_enabled: bool,
#[serde(default)]
pub is_pinned: bool,
}
fn default_comments_enabled() -> bool {
true
}
impl Default for PostContext {
fn default() -> Self {
Self {
comments_enabled: true,
comments_enabled: default_comments_enabled(),
is_pinned: false,
}
}
}

View file

@ -15,6 +15,7 @@ bitflags! {
const MANAGE_ROLES = 1 << 4;
const BANNED = 1 << 5;
const REQUESTED = 1 << 6;
const MANAGE_PINS = 1 << 7;
const _ = !0;
}