add: chat notifications

use sql_chanes/notifications_tag.sql; ignore first statement if you never used a preview commit
This commit is contained in:
trisua 2025-05-03 17:51:36 -04:00
parent a009ef9e34
commit 59cfec4819
22 changed files with 267 additions and 136 deletions

View file

@ -1,6 +1,6 @@
[package]
name = "tetratto"
version = "2.0.0"
version = "2.1.0"
edition = "2024"
[features]
@ -35,5 +35,8 @@ cf-turnstile = "0.2.0"
contrasted = "0.1.2"
futures-util = "0.3.31"
redis = { version = "0.30.0", features = ["aio", "tokio-comp"], optional = true }
redis = { version = "0.30.0", features = [
"aio",
"tokio-comp",
], optional = true }
tower_governor = "0.7.0"

View file

@ -22,6 +22,7 @@ version = "1.0.0"
"general:action.report" = "Report"
"general:action.manage" = "Manage"
"general:action.open" = "Open"
"general:action.copy_link" = "Copy link"
"general:label.safety" = "Safety"
"general:label.share" = "Share"
"general:action.add_account" = "Add account"
@ -157,3 +158,4 @@ version = "1.0.0"
"chats:label.viewing_old_messages" = "You're viewing old messages!"
"chats:label.go_back" = "Go back"
"chats:action.leave" = "Leave"
"chats:label.viewing_single_message" = "You're viewing a single message!"

View file

@ -109,7 +109,7 @@ hide_user_menu=true) }}
<div class="w-full flex flex-col gap-2" id="stream" style="padding: 1rem">
<turbo-frame
id="stream_body_frame"
src="/chats/{{ selected_community }}/{{ selected_channel }}/_stream?page={{ page }}"
src="/chats/{{ selected_community }}/{{ selected_channel }}/_stream?page={{ page }}&message={{ message }}"
></turbo-frame>
<form
@ -336,6 +336,7 @@ hide_user_menu=true) }}
<script>
window.CURRENT_PAGE = Number.parseInt("{{ page }}");
window.VIEWING_SINGLE = "{{ message }}".length > 0;
window.CHAT_PROPS = {
selected_community: "{{ selected_community }}",
selected_channel: "{{ selected_channel }}",
@ -457,6 +458,26 @@ hide_user_menu=true) }}
window.socket_id = window.CHAT_PROPS.selected_channel;
}
if (window.CHANNEL_NOTIFS_INTERVAL) {
window.clearInterval(window.CHANNEL_NOTIFS_INTERVAL);
}
window.CHANNEL_NOTIFS_INTERVAL = setInterval(() => {
if (!window.CHAT_PROPS.selected_channel) {
return;
}
if (!window.location.href.includes("{{ selected_channel }}")) {
window.clearInterval(window.CHANNEL_NOTIFS_INTERVAL);
return;
}
fetch(
`/api/v1/notifications/tag/chats/${window.CHAT_PROPS.selected_channel}`,
{ method: "DELETE" },
);
}, 10000);
window.socket.addEventListener("open", () => {
// auth
window.socket.send(
@ -480,7 +501,11 @@ hide_user_menu=true) }}
const msg = JSON.parse(event.data);
const [channel_id, data] = JSON.parse(msg.data);
if (msg.method === "Message" && window.CURRENT_PAGE === 0) {
if (
msg.method === "Message" &&
window.CURRENT_PAGE === 0 &&
window.VIEWING_SINGLE
) {
if (channel_id !== window.CHAT_PROPS.selected_channel) {
// message not for us... maybe send notification later
// something like /api/v1/messages/{id}/mark_unread

View file

@ -11,9 +11,20 @@
</div>
{% endif %}
{% for message in messages %}
{{ components::message(user=message[1], message=message[0], grouped=message[2]) }}
{% endfor %}
{% if message %}
<div class="card flex gap-2 small tertiary flex-wrap">
<b>{{ text "chats:label.viewing_single_message" }}</b>
<a href="/chats/{{ community }}/{{ channel }}/_stream?page={{ page }}" class="button small" onclick="window.VIEWING_SINGLE = false">
{{ text "chats:label.go_back" }}
</a>
</div>
{{ components::message(user=message_owner, message=message, grouped=false) }}
{% else %}
{% for message in messages %}
{{ components::message(user=message[1], message=message[0], grouped=message[2]) }}
{% endfor %}
{% endif %}
{% if messages|length > 0 %}
<div class="flex gap-2 w-full justify-center">

View file

@ -910,8 +910,7 @@ if state and state.data %}
{%- endmacro %} {% macro connection_url(key, value) -%} {% if value[0].data.url
%} {{ value[0].data.url }} {% elif key == "LastFm" %} https://last.fm/user/{{
value[0].data.name }} {% endif %} {%- endmacro %} {% macro
message_actions(can_manage_message, user, message) -%} {% if can_manage_message
or (user and user.id == message.owner) %}
message_actions(can_manage_message, user, message) -%}
<div class="dropdown">
<button
class="camo small"
@ -922,14 +921,30 @@ or (user and user.id == message.owner) %}
</button>
<div class="inner">
{% if can_manage_message or (user and user.id == message.owner) %}
<button class="red" onclick="delete_message('{{ message.id }}')">
{{ icon "trash" }}
<span>{{ text "general:action.delete" }}</span>
</button>
{% endif %}
<button
onclick="window.location.href = `${window.location.origin}/chats/{{ community }}/{{ channel }}?message={{ message.id }}`"
>
{{ icon "external-link" }}
<span>{{ text "general:action.open" }}</span>
</button>
<button
onclick="trigger('atto::copy_text', [`${window.location.origin}/chats/{{ community }}/{{ channel }}?message={{ message.id }}`])"
>
{{ icon "copy" }}
<span>{{ text "general:action.copy_link" }}</span>
</button>
</div>
</div>
{% endif %} {%- endmacro %} {% macro message(user, message,
can_manage_message=false, grouped=false) -%}
{%- endmacro %} {% macro message(user, message, can_manage_message=false,
grouped=false) -%}
<div
class="card secondary message flex gap-2 {% if grouped %}grouped{% endif %}"
id="message-{{ message.id }}"

View file

@ -3,7 +3,6 @@ pub mod images;
pub mod ipbans;
pub mod profile;
pub mod social;
pub mod subscriptions;
pub mod user_warnings;
use super::{LoginProps, RegisterProps};

View file

@ -1,58 +0,0 @@
use axum::{extract::Path, response::IntoResponse, Extension, Json};
use axum_extra::extract::CookieJar;
use tetratto_core::model::{ApiReturn, Error};
use crate::{get_user_from_token, State};
pub async fn update_last_message_request(
jar: CookieJar,
Extension(data): Extension<State>,
Json((channel_id, message_id)): Json<(usize, usize)>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let mut user = match get_user_from_token!(jar, data) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
user.subscriptions.insert(channel_id, message_id);
if let Err(e) = data
.update_user_subscriptions(user.id, user.subscriptions)
.await
{
return Json(e.into());
}
Json(ApiReturn {
ok: true,
message: "Subscription connection".to_string(),
payload: (),
})
}
pub async fn delete_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(channel): Path<usize>,
) -> impl IntoResponse {
let data = &(data.read().await).0;
let mut user = match get_user_from_token!(jar, data) {
Some(ua) => ua,
None => return Json(Error::NotAllowed.into()),
};
user.subscriptions.remove(&channel);
if let Err(e) = data
.update_user_subscriptions(user.id, user.subscriptions)
.await
{
return Json(e.into());
}
Json(ApiReturn {
ok: true,
message: "Subscription removed".to_string(),
payload: (),
})
}

View file

@ -210,6 +210,10 @@ pub fn routes() -> Router {
"/notifications/my",
delete(notifications::delete_all_request),
)
.route(
"/notifications/tag/{*tag}",
delete(notifications::delete_all_by_tag_request),
)
.route("/notifications/{id}", delete(notifications::delete_request))
.route(
"/notifications/{id}/read_status",
@ -303,15 +307,6 @@ pub fn routes() -> Router {
)
.route("/messages", post(channels::messages::create_request))
.route("/messages/{id}", delete(channels::messages::delete_request))
// subscriptions
.route(
"/auth/user/me/subscriptions/{channel_id}/{message_id}",
post(auth::subscriptions::update_last_message_request),
)
.route(
"/auth/user/me/subscriptions/{channel_id}",
delete(auth::subscriptions::delete_request),
)
}
#[derive(Deserialize)]

View file

@ -45,6 +45,27 @@ pub async fn delete_all_request(
}
}
pub async fn delete_all_by_tag_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path(tag): Path<String>,
) -> 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.delete_all_notifications_by_tag(&user, &tag).await {
Ok(_) => Json(ApiReturn {
ok: true,
message: "Notifications cleared".to_string(),
payload: (),
}),
Err(e) => Json(e.into()),
}
}
pub async fn update_read_status_request(
jar: CookieJar,
Extension(data): Extension<State>,

View file

@ -107,6 +107,7 @@ pub async fn app_request(
context.insert("selected_channel", &selected_channel);
context.insert("membership_role", &membership.role.bits());
context.insert("page", &props.page);
context.insert("message", &props.message);
context.insert(
"can_manage_channels",
@ -143,10 +144,10 @@ pub async fn stream_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path((community, channel)): Path<(usize, usize)>,
Query(props): Query<PaginatedQuery>,
Query(props): Query<ChatsAppQuery>,
) -> impl IntoResponse {
let data = data.read().await;
let mut user = match get_user_from_token!(jar, data.0) {
let user = match get_user_from_token!(jar, data.0) {
Some(ua) => ua,
None => {
return Err(Html(
@ -156,32 +157,6 @@ pub async fn stream_request(
};
let ignore_users = data.0.get_userblocks_receivers(user.id).await;
let messages = match data
.0
.get_messages_by_channel(channel, 24, props.page)
.await
{
Ok(p) => match data.0.fill_messages(p, &ignore_users).await {
Ok(p) => p,
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)),
};
if props.page == 0 {
if let Some(ref last_message) = messages.get(messages.len() - 1) {
user.subscriptions.insert(channel, last_message.0.id);
// maybe make update_user_subscriptions take a reference to avoid cloning
if let Err(e) = data
.0
.update_user_subscriptions(user.id, user.subscriptions.clone())
.await
{
return Err(Html(render_error(e, &jar, &data, &Some(user)).await));
}
}
}
let membership = match data
.0
@ -195,10 +170,48 @@ pub async fn stream_request(
let can_manage_messages = membership.role.check(CommunityPermission::MANAGE_MESSAGES)
| user.permissions.check(FinePermission::MANAGE_MESSAGES);
let messages = if props.message == 0 {
match data
.0
.get_messages_by_channel(channel, 24, props.page)
.await
{
Ok(p) => match data.0.fill_messages(p, &ignore_users).await {
Ok(p) => p,
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)),
}
} else {
Vec::new()
};
let message = if props.message == 0 {
None
} else {
Some(match data.0.get_message_by_id(props.message).await {
Ok(p) => p,
Err(e) => return Err(Html(render_error(e, &jar, &data, &Some(user)).await)),
})
};
let message_owner = if let Some(ref message) = message {
Some(match data.0.get_user_by_id(message.owner).await {
Ok(p) => p,
Err(e) => return Err(Html(render_error(e, &jar, &data, &Some(user)).await)),
})
} else {
None
};
let lang = get_lang!(jar, data.0);
let mut context = initial_context(&data.0.0, lang, &Some(user)).await;
context.insert("messages", &messages);
context.insert("message", &message);
context.insert("message_owner", &message_owner);
context.insert("can_manage_messages", &can_manage_messages);
context.insert("page", &props.page);
@ -213,7 +226,7 @@ pub async fn stream_request(
pub async fn message_request(
jar: CookieJar,
Extension(data): Extension<State>,
Path((community, _)): Path<(usize, usize)>,
Path((community, channel)): Path<(usize, usize)>,
Json(req): Json<RenderMessage>,
) -> impl IntoResponse {
let data = data.read().await;
@ -261,6 +274,9 @@ pub async fn message_request(
context.insert("message", &message);
context.insert("user", &owner);
context.insert("channel", &channel);
context.insert("community", &community);
// return
Ok(Html(data.1.render("chats/message.html", &context).unwrap()))
}

View file

@ -130,6 +130,8 @@ pub struct ChatsAppQuery {
pub page: usize,
#[serde(default)]
pub nav: bool,
#[serde(default)]
pub message: usize,
}
#[derive(Deserialize)]