add: block list stacks

This commit is contained in:
trisua 2025-06-15 11:52:44 -04:00
parent 9bb5f38f76
commit b71ae1f5a4
28 changed files with 700 additions and 219 deletions

View file

@ -113,7 +113,7 @@ pub const CHATS_MESSAGE: &str = include_str!("./public/html/chats/message.lisp")
pub const CHATS_CHANNELS: &str = include_str!("./public/html/chats/channels.lisp");
pub const STACKS_LIST: &str = include_str!("./public/html/stacks/list.lisp");
pub const STACKS_POSTS: &str = include_str!("./public/html/stacks/posts.lisp");
pub const STACKS_FEED: &str = include_str!("./public/html/stacks/feed.lisp");
pub const STACKS_MANAGE: &str = include_str!("./public/html/stacks/manage.lisp");
pub const FORGE_HOME: &str = include_str!("./public/html/forge/home.lisp");
@ -401,7 +401,7 @@ pub(crate) async fn write_assets(config: &Config) -> PathBufD {
write_template!(html_path->"chats/channels.html"(crate::assets::CHATS_CHANNELS) --config=config --lisp plugins);
write_template!(html_path->"stacks/list.html"(crate::assets::STACKS_LIST) -d "stacks" --config=config --lisp plugins);
write_template!(html_path->"stacks/posts.html"(crate::assets::STACKS_POSTS) --config=config --lisp plugins);
write_template!(html_path->"stacks/feed.html"(crate::assets::STACKS_FEED) --config=config --lisp plugins);
write_template!(html_path->"stacks/manage.html"(crate::assets::STACKS_MANAGE) --config=config --lisp plugins);
write_template!(html_path->"forge/home.html"(crate::assets::FORGE_HOME) -d "forge" --config=config --lisp plugins);

View file

@ -204,6 +204,8 @@ version = "1.0.0"
"stacks:tab.users" = "Users"
"stacks:label.add_user" = "Add user"
"stacks:label.remove" = "Remove"
"stacks:label.block_all" = "Block all"
"stacks:label.unblock_all" = "Unblock all"
"forge:label.my_forges" = "My forges"
"forge:label.create_new" = "Create new forge"

View file

@ -203,11 +203,16 @@ macro_rules! check_user_blocked_or_private {
// check if we're blocked
if let Some(ref ua) = $user {
if $data
if ($data
.0
.get_userblock_by_initiator_receiver($other_user.id, ua.id)
.await
.is_ok()
| $data
.0
.get_user_stack_blocked_users($other_user.id)
.await
.contains(&ua.id))
&& !ua.permissions.check(FinePermission::MANAGE_USERS)
{
let lang = get_lang!($jar, $data.0);
@ -291,10 +296,14 @@ macro_rules! check_user_blocked_or_private {
($user:expr, $other_user:ident, $data:ident, @api) => {
// check if we're blocked
if let Some(ref ua) = $user {
if $data
if ($data
.get_userblock_by_initiator_receiver($other_user.id, ua.id)
.await
.is_ok()
| $data
.get_user_stack_blocked_users($other_user.id)
.await
.contains(&ua.id))
&& !ua
.permissions
.check(tetratto_core::model::permissions::FinePermission::MANAGE_USERS)
@ -338,6 +347,7 @@ macro_rules! ignore_users_gen {
[
$data.0.get_userblocks_receivers(ua.id).await,
$data.0.get_userblocks_initiator_by_receivers(ua.id).await,
$data.0.get_user_stack_blocked_users(ua.id).await,
]
.concat()
} else {
@ -345,16 +355,17 @@ macro_rules! ignore_users_gen {
}
};
($user:ident!, $data:ident) => {
($user:ident!, $data:ident) => {{
[
$data.0.get_userblocks_receivers($user.id).await,
$data
.0
.get_userblocks_initiator_by_receivers($user.id)
.await,
$data.0.get_user_stack_blocked_users($user.id).await,
]
.concat()
};
}};
($user:ident!, #$data:ident) => {
[

View file

@ -56,7 +56,8 @@
animation: popin ease-in-out 1 0.15s forwards running;
}
.lightbox a {
.lightbox a,
.lightbox img {
--padding: 2rem;
cursor: zoom-in;
max-height: calc(100dvh - var(--padding));
@ -684,6 +685,9 @@ nav .button:not(.title):not(.active):hover {
gap: var(--pad-2);
align-items: center;
justify-content: space-between;
position: sticky;
top: 0;
z-index: 1;
}
/* mobile nav chip nav */

View file

@ -1817,3 +1817,20 @@
("class" "no_p_margin")
(text "{{ post.title|markdown|safe }}"))))
(text "{%- endmacro %}")
(text "{% macro stack_listing(stack) -%}")
(a
("href" "/stacks/{{ stack.id }}")
("class" "card secondary flex flex-col gap-2")
(div
("class" "flex items-center gap-2")
(text "{{ icon \"list\" }}")
(b
(text "{{ stack.name }}")))
(span
(text "Created ")
(span
("class" "date")
(text "{{ stack.created }}"))
(text "; {{ stack.privacy }}; {{ stack.users|length }} users")))
(text "{%- endmacro %}")

View file

@ -101,15 +101,15 @@
(li
(a ("href" "https://trisua.com/t/tetratto") (text "Source code")))
(li
(a ("href" "https://tetratto.com/reference/tetratto/index.html") (text "Source code reference")))
(a ("href" "https://tetratto.com/reference/tetratto/index.html") ("data-turbo" "false") (text "Source code reference")))
(li
(a ("href" "https://tetratto.com/reference/tetratto/model/struct.ApiReturn.html") (text "API response structure")))
(a ("href" "https://tetratto.com/reference/tetratto/model/struct.ApiReturn.html") ("data-turbo" "false") (text "API response structure")))
(li
(a ("href" "https://tetratto.com/reference/tetratto/model/oauth/enum.AppScope.html") (text "App scopes")))
(a ("href" "https://tetratto.com/reference/tetratto/model/oauth/enum.AppScope.html") ("data-turbo" "false") (text "App scopes")))
(li
(a ("href" "https://tetratto.com/reference/tetratto/model/permissions/struct.FinePermission.html") (text "User permissions")))
(a ("href" "https://tetratto.com/reference/tetratto/model/permissions/struct.FinePermission.html") ("data-turbo" "false") (text "User permissions")))
(li
(a ("href" "https://tetratto.com/reference/tetratto/model/communities_permissions/struct.CommunityPermission.html") (text "Community member permissions")))
(a ("href" "https://tetratto.com/reference/tetratto/model/communities_permissions/struct.CommunityPermission.html") ("data-turbo" "false") (text "Community member permissions")))
(li
(a ("href" "https://tetratto.com/forge/tetratto") (text "Report issues")))))))

View file

@ -388,6 +388,22 @@
(text "{{ icon \"arrow-left\" }}")
(span
(text "{{ text \"general:action.back\" }}")))
; stack blocks
(div
("class" "card-nest")
(div
("class" "card flex items-center gap-2 small")
(text "{{ icon \"layers\" }}")
(span
(text "{{ text \"stacks:link.stacks\" }}")))
(div
("class" "card flex flex-col gap-2")
(text "{% for stack in stackblocks %}")
(text "{{ components::stack_listing(stack=stack) }}")
(text "{% endfor %}")))
; user blocks
(div
("class" "card-nest")
(div

View file

@ -0,0 +1,85 @@
(text "{% extends \"root.html\" %} {% block head %}")
(title
(text "{{ stack.name }} - {{ config.name }}"))
(text "{% endblock %} {% block body %} {{ macros::nav() }}")
(main
("class" "flex flex-col gap-2")
(text "{{ macros::timelines_nav(selected=\"stacks\") }}")
(div
("class" "card-nest w-full")
(div
("class" "card small flex items-center justify-between gap-2")
(div
("class" "flex items-center gap-2")
(text "{{ icon \"list\" }}")
(span
(text "{{ stack.name }}")))
(text "{% if user and user.id == stack.owner -%}")
(a
("href" "/stacks/{{ stack.id }}/manage")
("class" "button lowered small")
(text "{{ icon \"pencil\" }}")
(span
(text "{{ text \"general:action.manage\" }}")))
(text "{%- endif %}"))
(div
("class" "card w-full flex flex-col gap-2")
(text "{% if list|length == 0 -%}")
(p
(text "No items yet! Maybe ")
(a
("href" "/stacks/{{ stack.id }}/manage#/users")
(text "add a user to this stack"))
(text "!"))
(text "{%- endif %}")
(text "{% if stack.mode == 'BlockList' -%}")
(text "{% if not is_blocked -%}")
(button
("onclick" "block_all()")
(str (text "stacks:label.block_all")))
(text "{% else %}")
(button
("onclick" "block_all(false)")
(str (text "stacks:label.unblock_all")))
(text "{%- endif %}")
(div
("class" "flex gap-2 flex-wrap w-full")
(text "{% for user in list %} {{ components::user_plate(user=user, secondary=true) }} {% endfor %}"))
(text "{% else %}")
(text "{% for post in list %}
{% if post[2].read_access == \"Everybody\" -%}
{% 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], question=post[4], secondary=true, community=post[2], poll=post[5]) }}
{%- endif %} {%- endif %} {% endfor %}")
(text "{%- endif %} {{ components::pagination(page=page, items=list|length) }}"))))
(script
(text "async function block_all(block = true) {
if (
!(await trigger(\"atto::confirm\", [
\"Are you sure you would like to do this?\",
]))
) {
return;
}
fetch(\"/api/v1/stacks/{{ stack.id }}/block\", {
method: block ? \"POST\" : \"DELETE\",
})
.then((res) => res.json())
.then((res) => {
trigger(\"atto::toast\", [
res.ok ? \"success\" : \"error\",
res.message,
]);
if (res.ok) {
window.location.href = \"/settings#/account/blocks\";
}
});
}"))
(text "{% endblock %}")

View file

@ -44,20 +44,7 @@
(div
("class" "card flex flex-col gap-2")
(text "{% for item in list %}")
(a
("href" "/stacks/{{ item.id }}")
("class" "card secondary flex flex-col gap-2")
(div
("class" "flex items-center gap-2")
(text "{{ icon \"list\" }}")
(b
(text "{{ item.name }}")))
(span
(text "Created ")
(span
("class" "date")
(text "{{ item.created }}"))
(text "; {{ item.privacy }}; {{ item.users|length }} users")))
(text "{{ components::stack_listing(stack=item) }}")
(text "{% endfor %}"))))
(script

View file

@ -63,7 +63,11 @@
(option
("value" "Exclude")
("selected" "{% if stack.mode == 'Exclude' -%}true{% else %}false{%- endif %}")
(text "Exclude")))))
(text "Exclude"))
(option
("value" "BlockList")
("selected" "{% if stack.mode == 'BlockList' -%}true{% else %}false{%- endif %}")
(text "Block list")))))
(div
("class" "card-nest")
("ui_ident" "sort")

View file

@ -1,37 +0,0 @@
(text "{% extends \"root.html\" %} {% block head %}")
(title
(text "{{ stack.name }} - {{ config.name }}"))
(text "{% endblock %} {% block body %} {{ macros::nav() }}")
(main
("class" "flex flex-col gap-2")
(text "{{ macros::timelines_nav(selected=\"stacks\") }}")
(div
("class" "card-nest w-full")
(div
("class" "card small flex items-center justify-between gap-2")
(div
("class" "flex items-center gap-2")
(text "{{ icon \"list\" }}")
(span
(text "{{ stack.name }}")))
(text "{% if user and user.id == stack.owner -%}")
(a
("href" "/stacks/{{ stack.id }}/manage")
("class" "button lowered small")
(text "{{ icon \"pencil\" }}")
(span
(text "{{ text \"general:action.manage\" }}")))
(text "{%- endif %}"))
(div
("class" "card w-full flex flex-col gap-2")
(text "{% if list|length == 0 -%}")
(p
(text "No posts yet! Maybe ")
(a
("href" "/stacks/{{ stack.id }}/manage#/users")
(text "add a user to this stack"))
(text "!"))
(text "{%- endif %} {% for post in list %} {% if post[2].read_access == \"Everybody\" -%} {% 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], question=post[4], secondary=true, community=post[2], poll=post[5]) }} {%- endif %} {%- endif %} {% endfor %} {{ components::pagination(page=page, items=list|length) }}"))))
(text "{% endblock %}")

View file

@ -1104,24 +1104,9 @@ ${option.input_element_type === "textarea" ? `${option.value}</textarea>` : ""}
);
// lightbox
self.define("lightbox_open", async (_, src) => {
self.define("lightbox_open", (_, src) => {
document.getElementById("lightbox_img").src = src;
document.getElementById("lightbox_img_a").href = src;
await (async () => {
return new Promise((resolve, reject) => {
let idx = 0;
const inter = setInterval(() => {
idx += 1;
if (document.getElementById("lightbox_img").complete) {
console.log(`img loaded (took ${idx})`);
clearInterval(inter);
return resolve();
}
}, 25);
});
})();
document.getElementById("lightbox").classList.remove("hidden");
});

View file

@ -537,8 +537,11 @@ pub fn routes() -> Router {
.route("/stacks/{id}/privacy", post(stacks::update_privacy_request))
.route("/stacks/{id}/mode", post(stacks::update_mode_request))
.route("/stacks/{id}/sort", post(stacks::update_sort_request))
.route("/stacks/{id}/users", get(stacks::get_users_request))
.route("/stacks/{id}/users", post(stacks::add_user_request))
.route("/stacks/{id}/users", delete(stacks::remove_user_request))
.route("/stacks/{id}/block", post(stacks::block_request))
.route("/stacks/{id}/block", delete(stacks::unblock_request))
.route("/stacks/{id}", delete(stacks::delete_request))
// uploads
.route("/uploads/{id}", get(uploads::get_request))

View file

@ -1,7 +1,16 @@
use crate::{State, get_user_from_token};
use axum::{Extension, Json, extract::Path, response::IntoResponse};
use crate::{get_user_from_token, routes::pages::PaginatedQuery, State};
use axum::{
extract::{Path, Query},
response::IntoResponse,
Extension, Json,
};
use axum_extra::extract::CookieJar;
use tetratto_core::model::{oauth, stacks::UserStack, ApiReturn, Error};
use tetratto_core::model::{
oauth,
permissions::FinePermission,
stacks::{StackBlock, StackPrivacy, UserStack},
ApiReturn, Error,
};
use super::{
AddOrRemoveStackUser, CreateStack, UpdateStackMode, UpdateStackName, UpdateStackPrivacy,
UpdateStackSort,
@ -221,3 +230,93 @@ pub async fn delete_request(
Err(e) => Json(e.into()),
}
}
pub async fn get_users_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
Query(props): Query<PaginatedQuery>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data, oauth::AppScope::UserReadProfiles) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
let stack = match data.get_stack_by_id(id).await {
Ok(s) => s,
Err(e) => return Json(e.into()),
};
if stack.privacy == StackPrivacy::Private
&& user.id != stack.owner
&& !user.permissions.check(FinePermission::MANAGE_STACKS)
{
return Json(Error::NotAllowed.into());
}
match data.get_stack_users(id, 12, props.page).await {
Ok(users) => Json(ApiReturn {
ok: true,
message: "Success".to_string(),
payload: Some({
let mut out = Vec::new();
for mut u in users.clone() {
u.clean();
out.push(u)
}
out
}),
}),
Err(e) => Json(e.into()),
}
}
pub async fn block_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data, oauth::AppScope::UserReadProfiles) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
match data.create_stackblock(StackBlock::new(user.id, id)).await {
Ok(_) => Json(ApiReturn {
ok: true,
message: "Success".to_string(),
payload: (),
}),
Err(e) => Json(e.into()),
}
}
pub async fn unblock_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let user = match get_user_from_token!(jar, data, oauth::AppScope::UserReadProfiles) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
let block = match data.get_stackblock_by_initiator_stack(user.id, id).await {
Ok(b) => b,
Err(e) => return Json(e.into()),
};
match data.delete_stackblock(block.id, user).await {
Ok(_) => Json(ApiReturn {
ok: true,
message: "Success".to_string(),
payload: (),
}),
Err(e) => Json(e.into()),
}
}

View file

@ -126,7 +126,7 @@ pub fn routes() -> Router {
.route("/developer/app/{id}", get(developer::app_request))
// stacks
.route("/stacks", get(stacks::list_request))
.route("/stacks/{id}", get(stacks::posts_request))
.route("/stacks/{id}", get(stacks::feed_request))
.route("/stacks/{id}/manage", get(stacks::manage_request))
}

View file

@ -80,6 +80,19 @@ pub async fn settings_request(
Err(e) => return Err(Html(render_error(e, &jar, &data, &None).await)),
};
let stackblocks = {
let mut out = Vec::new();
for block in data.0.get_stackblocks_by_initiator(profile.id).await {
out.push(match data.0.get_stack_by_id(block.stack).await {
Ok(s) => s,
Err(_) => continue,
});
}
out
};
let uploads = match data.0.get_uploads_by_owner(profile.id, 12, req.page).await {
Ok(ua) => ua,
Err(e) => {
@ -98,6 +111,7 @@ pub async fn settings_request(
context.insert("stacks", &stacks);
context.insert("following", &following);
context.insert("blocks", &blocks);
context.insert("stackblocks", &stackblocks);
context.insert(
"user_tokens_serde",
&serde_json::to_string(&tokens)
@ -128,59 +142,37 @@ pub async fn settings_request(
)
.unwrap();
let light = serde_json::Value::from("Light");
let mut profile_theme = settings_map
.get("profile_theme")
.unwrap_or(&light)
.as_str()
.unwrap();
if let Some(color_surface) = settings_map.get("theme_color_surface") {
let color_surface = color_surface.as_str().unwrap();
for setting in &settings_map {
if !setting.0.starts_with("theme_color_text")
| (setting.0 == "theme_color_text_primary")
| (setting.0 == "theme_color_text_secondary")
{
continue;
}
if profile_theme.is_empty() | (profile_theme == "Auto") {
profile_theme = "Light";
}
let value = setting.1.as_str().unwrap();
let default_surface = serde_json::Value::from(if profile_theme == "Light" {
"#f3f2f1"
if !value.starts_with("#") {
// we can only parse hex right now
continue;
}
let c1 = Color::from(color_surface);
let c2 = Color::from(value);
let contrast = c1.contrast(&c2);
if contrast < MINIMUM_CONTRAST_THRESHOLD {
failing_color_keys.push((setting.0, contrast));
}
}
context.insert("failing_color_keys", &failing_color_keys);
} else {
"#19171c"
});
let mut color_surface = settings_map
.get("theme_color_surface")
.unwrap_or(&default_surface)
.as_str()
.unwrap();
if color_surface.is_empty() {
color_surface = default_surface.as_str().unwrap();
context.insert("failing_color_keys", &Vec::<&str>::new());
}
for setting in &settings_map {
if !setting.0.starts_with("theme_color_text")
| (setting.0 == "theme_color_text_primary")
| (setting.0 == "theme_color_text_secondary")
{
continue;
}
let value = setting.1.as_str().unwrap();
if !value.starts_with("#") {
// we can only parse hex right now
continue;
}
let c1 = Color::from(color_surface);
let c2 = Color::from(value);
let contrast = c1.contrast(&c2);
if contrast < MINIMUM_CONTRAST_THRESHOLD {
failing_color_keys.push((setting.0, contrast));
}
}
context.insert("failing_color_keys", &failing_color_keys);
// return
Ok(Html(
data.1.render("profile/settings.html", &context).unwrap(),

View file

@ -4,7 +4,12 @@ use axum::{
Extension,
};
use axum_extra::extract::CookieJar;
use tetratto_core::model::{permissions::FinePermission, stacks::StackPrivacy, Error, auth::User};
use tetratto_core::model::{
auth::User,
permissions::FinePermission,
stacks::{StackMode, StackPrivacy},
Error,
};
use crate::{assets::initial_context, get_lang, get_user_from_token, State};
use super::{render_error, PaginatedQuery};
@ -35,7 +40,7 @@ pub async fn list_request(jar: CookieJar, Extension(data): Extension<State>) ->
}
/// `/stacks/{id}`
pub async fn posts_request(
pub async fn feed_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(id): Path<usize>,
@ -65,32 +70,50 @@ pub async fn posts_request(
));
}
let ignore_users = crate::ignore_users_gen!(user!, data);
let list = match data
.0
.get_stack_posts(
user.id,
stack.id,
12,
req.page,
&ignore_users,
&Some(user.clone()),
)
.await
{
Ok(l) => l,
Err(e) => return Err(Html(render_error(e, &jar, &data, &Some(user)).await)),
};
let lang = get_lang!(jar, data.0);
let mut context = initial_context(&data.0.0.0, lang, &Some(user)).await;
let mut context = initial_context(&data.0.0.0, lang, &Some(user.clone())).await;
context.insert("page", &req.page);
context.insert("stack", &stack);
context.insert("list", &list);
if stack.mode == StackMode::BlockList {
let list = match data.0.get_stack_users(stack.id, 12, req.page).await {
Ok(l) => l,
Err(e) => return Err(Html(render_error(e, &jar, &data, &Some(user)).await)),
};
context.insert("list", &list);
context.insert(
"is_blocked",
&data
.0
.get_stackblock_by_initiator_stack(user.id, stack.id)
.await
.is_ok(),
);
} else {
let ignore_users = crate::ignore_users_gen!(user!, data);
let list = match data
.0
.get_stack_posts(
user.id,
stack.id,
12,
req.page,
&ignore_users,
&Some(user.clone()),
)
.await
{
Ok(l) => l,
Err(e) => return Err(Html(render_error(e, &jar, &data, &Some(user)).await)),
};
context.insert("list", &list);
}
// return
Ok(Html(data.1.render("stacks/posts.html", &context).unwrap()))
Ok(Html(data.1.render("stacks/feed.html", &context).unwrap()))
}
/// `/stacks/{id}/manage`