This commit is contained in:
2026-08-08 19:56:57 +02:00
parent d1f9234457
commit 42ab990f7d
23 changed files with 681 additions and 93 deletions
+16
View File
@@ -42,12 +42,28 @@ pub struct ChannelResponse {
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unread_count: Option<u64>,
/// None : contexte sans permissions (champ ignoré dans le JSON).
/// Some(value) : valeur de computed_permission (0 si absente).
#[serde(skip_serializing_if = "Option::is_none")]
pub permission: Option<u64>,
}
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct ReadStateResponse {
pub channel_id: Uuid,
pub last_read_message_id: Option<Uuid>,
pub updated_at: Option<DateTime<Utc>>,
pub unread_count: u64,
}
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct SetReadStateRequest {
pub last_read_message_id: Option<Uuid>,
}
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct SetChannelPermissionRequest {
/// Bitmask des permissions à appliquer.
+2
View File
@@ -28,6 +28,8 @@ pub struct ServerResponse {
pub is_default: bool,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unread_count: Option<u64>,
}
#[derive(Debug, Serialize, Deserialize, ToSchema)]
+1 -3
View File
@@ -1,7 +1,5 @@
use migration::{Migrator, MigratorTrait};
use oxspeak_server_lib::config::AppConfig;
use oxspeak_server_lib::core::App;
use oxspeak_server_lib::database::Database;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
@@ -10,7 +8,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.with_env_filter(
std::env::var("RUST_LOG")
// .unwrap_or_else(|_| "info,sqlx=debug,sea_orm=debug,sea_orm_migration=info".into()),
.unwrap_or_else(|_| "info,sqlx=info,sea_orm=info,sea_orm_migration=info".into()),
.unwrap_or_else(|_| "info,sqlx=debug,sea_orm=debug,sea_orm_migration=debug".into()),
)
.with_target(true)
.with_level(true)
+33
View File
@@ -0,0 +1,33 @@
use sea_orm::entity::prelude::*;
use sea_orm::prelude::async_trait::async_trait;
#[sea_orm::model]
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "channel_user_read_state")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub id: Uuid,
pub channel_id: Uuid,
pub user_id: Uuid,
pub last_read_message_id: Option<Uuid>,
pub updated_at: DateTimeUtc,
#[sea_orm(
belongs_to,
from = "channel_id",
to = "id",
on_update = "NoAction",
on_delete = "Cascade"
)]
pub channel: HasOne<super::channel::Entity>,
#[sea_orm(
belongs_to,
from = "user_id",
to = "id",
on_update = "NoAction",
on_delete = "Cascade"
)]
pub user: HasOne<super::user::Entity>,
}
#[async_trait]
impl ActiveModelBehavior for ActiveModel {}
+1
View File
@@ -7,6 +7,7 @@ pub mod category;
pub mod channel;
pub mod channel_role_permission;
pub mod channel_user;
pub mod channel_user_read_state;
pub mod channel_user_permission;
pub mod computed_permission;
pub mod message;
+1
View File
@@ -4,6 +4,7 @@ pub use super::attachment::Entity as Attachment;
pub use super::category::Entity as Category;
pub use super::channel::Entity as Channel;
pub use super::channel_user::Entity as ChannelUser;
pub use super::channel_user_read_state::Entity as ChannelUserReadState;
pub use super::computed_permission::Entity as ComputedPermission;
pub use super::message::Entity as Message;
pub use super::role::Entity as Group;
+6
View File
@@ -4,6 +4,7 @@ use crate::repositories::category::CategoryRepository;
use crate::repositories::channel::ChannelRepository;
use crate::repositories::computed_permission::ComputedPermissionRepository;
use crate::repositories::message::MessageRepository;
use crate::repositories::read_state::ReadStateRepository;
use crate::repositories::role::RoleRepository;
use crate::repositories::server::ServerRepository;
use crate::repositories::server_item_order::ServerItemOrderRepository;
@@ -16,6 +17,7 @@ mod category;
mod channel;
mod computed_permission;
mod message;
mod read_state;
mod role;
mod server;
mod server_item_order;
@@ -35,6 +37,7 @@ pub struct Repositories {
pub channel: ChannelRepository,
pub role: RoleRepository,
pub message: MessageRepository,
pub read_state: ReadStateRepository,
pub user: UserRepository,
pub computed_permission: ComputedPermissionRepository,
pub server_item_order: ServerItemOrderRepository,
@@ -61,6 +64,9 @@ impl Repositories {
message: MessageRepository {
context: context.clone(),
},
read_state: ReadStateRepository {
context: context.clone(),
},
user: UserRepository {
context: context.clone(),
},
+152
View File
@@ -0,0 +1,152 @@
use crate::models::{channel, channel_user_read_state, message};
use crate::repositories::{AnyResult, RepositoryContext};
use chrono::Utc;
use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, QueryFilter, QuerySelect, Set};
use std::collections::HashMap;
use std::sync::Arc;
use uuid::Uuid;
#[derive(Clone, Debug)]
pub struct ReadStateRepository {
pub context: Arc<RepositoryContext>,
}
impl ReadStateRepository {
pub async fn get(
&self,
channel_id: Uuid,
user_id: Uuid,
) -> AnyResult<Option<channel_user_read_state::Model>> {
Ok(channel_user_read_state::Entity::find()
.filter(channel_user_read_state::Column::ChannelId.eq(channel_id))
.filter(channel_user_read_state::Column::UserId.eq(user_id))
.one(&self.context.db)
.await?)
}
pub async fn set(
&self,
channel_id: Uuid,
user_id: Uuid,
last_read_message_id: Option<Uuid>,
) -> AnyResult<channel_user_read_state::Model> {
let now = Utc::now();
let active = channel_user_read_state::ActiveModel {
id: Set(Uuid::now_v7()),
channel_id: Set(channel_id),
user_id: Set(user_id),
last_read_message_id: Set(last_read_message_id),
updated_at: Set(now),
};
if let Some(existing) = self.get(channel_id, user_id).await? {
if existing.last_read_message_id >= last_read_message_id {
return Ok(existing);
}
let mut active: channel_user_read_state::ActiveModel = existing.into();
active.last_read_message_id = Set(last_read_message_id);
active.updated_at = Set(now);
return Ok(active.update(&self.context.db).await?);
}
Ok(active.insert(&self.context.db).await?)
}
pub async fn unread_counts(
&self,
channel_ids: &[Uuid],
user_id: Uuid,
) -> AnyResult<HashMap<Uuid, u64>> {
if channel_ids.is_empty() {
return Ok(HashMap::new());
}
let states = channel_user_read_state::Entity::find()
.filter(channel_user_read_state::Column::UserId.eq(user_id))
.filter(channel_user_read_state::Column::ChannelId.is_in(channel_ids.to_vec()))
.all(&self.context.db)
.await?;
let cursors: HashMap<Uuid, Option<Uuid>> = states
.into_iter()
.map(|state| (state.channel_id, state.last_read_message_id))
.collect();
let messages = message::Entity::find()
.select_only()
.column(message::Column::ChannelId)
.column(message::Column::Id)
.filter(message::Column::ChannelId.is_in(channel_ids.to_vec()))
.into_tuple::<(Uuid, Uuid)>()
.all(&self.context.db)
.await?;
let mut counts = HashMap::new();
for (channel_id, message_id) in messages {
let unread = match cursors.get(&channel_id) {
Some(Some(cursor)) => message_id > *cursor,
_ => true,
};
if unread {
*counts.entry(channel_id).or_insert(0) += 1;
}
}
Ok(counts)
}
pub async fn unread_counts_by_server(
&self,
user_id: Uuid,
) -> AnyResult<HashMap<Uuid, u64>> {
let channels = channel::Entity::find()
.select_only()
.column(channel::Column::Id)
.column(channel::Column::ServerId)
.filter(channel::Column::ServerId.is_not_null())
.into_tuple::<(Uuid, Option<Uuid>)>()
.all(&self.context.db)
.await?;
let channel_to_server: HashMap<Uuid, Uuid> = channels
.into_iter()
.filter_map(|(channel_id, server_id)| server_id.map(|server_id| (channel_id, server_id)))
.collect();
if channel_to_server.is_empty() {
return Ok(HashMap::new());
}
let channel_ids: Vec<Uuid> = channel_to_server.keys().copied().collect();
let states = channel_user_read_state::Entity::find()
.filter(channel_user_read_state::Column::UserId.eq(user_id))
.filter(channel_user_read_state::Column::ChannelId.is_in(channel_ids.clone()))
.all(&self.context.db)
.await?;
let cursors: HashMap<Uuid, Option<Uuid>> = states
.into_iter()
.map(|state| (state.channel_id, state.last_read_message_id))
.collect();
let messages = message::Entity::find()
.select_only()
.column(message::Column::ChannelId)
.column(message::Column::Id)
.filter(message::Column::ChannelId.is_in(channel_ids))
.into_tuple::<(Uuid, Uuid)>()
.all(&self.context.db)
.await?;
let mut counts = HashMap::new();
for (channel_id, message_id) in messages {
let unread = match cursors.get(&channel_id) {
Some(Some(cursor)) => message_id > *cursor,
_ => true,
};
if unread {
let server_id = channel_to_server[&channel_id];
*counts.entry(server_id).or_insert(0) += 1;
}
}
Ok(counts)
}
}
+32 -2
View File
@@ -1,8 +1,8 @@
use crate::models::{category, channel, computed_permission, server_item_order};
use crate::models::{category, channel, channel_user_read_state, computed_permission, message, server_item_order};
use crate::permissions::ChannelPermission;
use crate::repositories::types::{CategoryWithPermissions, ChannelWithPermissions, ServerTreeData};
use crate::repositories::{AnyResult, RepositoryContext};
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter, QueryOrder};
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter, QueryOrder, QuerySelect};
use std::collections::HashMap;
use std::sync::Arc;
use uuid::Uuid;
@@ -70,6 +70,35 @@ impl ServerTreeRepository {
})
.collect();
let channel_ids: Vec<Uuid> = channel_models.iter().map(|channel| channel.id).collect();
let read_states = channel_user_read_state::Entity::find()
.filter(channel_user_read_state::Column::UserId.eq(user_id))
.filter(channel_user_read_state::Column::ChannelId.is_in(channel_ids.clone()))
.all(&self.context.db)
.await?;
let cursors: HashMap<Uuid, Option<Uuid>> = read_states
.into_iter()
.map(|state| (state.channel_id, state.last_read_message_id))
.collect();
let messages = message::Entity::find()
.select_only()
.column(message::Column::ChannelId)
.column(message::Column::Id)
.filter(message::Column::ChannelId.is_in(channel_ids))
.into_tuple::<(Uuid, Uuid)>()
.all(&self.context.db)
.await?;
let mut unread_counts = HashMap::new();
for (channel_id, message_id) in messages {
let unread = match cursors.get(&channel_id) {
Some(Some(cursor)) => message_id > *cursor,
_ => true,
};
if unread {
*unread_counts.entry(channel_id).or_insert(0) += 1;
}
}
let channels = channel_models
.into_iter()
.map(|channel| {
@@ -87,6 +116,7 @@ impl ServerTreeRepository {
orders,
categories,
channels,
unread_counts,
})
}
}
+1
View File
@@ -76,4 +76,5 @@ pub struct ServerTreeData {
pub orders: Vec<server_item_order::Model>,
pub categories: Vec<CategoryWithPermissions>,
pub channels: Vec<ChannelWithPermissions>,
pub unread_counts: std::collections::HashMap<Uuid, u64>,
}
+88 -2
View File
@@ -1,9 +1,10 @@
use crate::core::state::AppState;
use crate::http::context::Superuser;
use crate::http::context::{CurrentUser, Superuser};
use crate::http::error::HTTPError;
use crate::domain::dto::channel::{
ChannelQueryParams, ChannelResponse, ChannelPermissionsResponse, ChannelRolePermissionResponse,
ChannelUserPermissionResponse, CreateChannelRequest, SetChannelPermissionRequest,
ChannelUserPermissionResponse, CreateChannelRequest, ReadStateResponse,
SetChannelPermissionRequest, SetReadStateRequest,
UpdateChannelRequest,
};
use crate::routes::channel::mapper;
@@ -41,6 +42,91 @@ pub async fn get_all(
))
}
#[utoipa::path(
get,
path = "/channels/{channel_id}/read-state",
params(("channel_id" = Uuid, Path, description = "ID du canal")),
responses((status = 200, body = ReadStateResponse), (status = 404, description = "Canal non trouvé")),
tag = "Channels",
security(("bearerAuth" = []))
)]
pub async fn get_read_state(
user: CurrentUser,
State(state): State<AppState>,
Path(channel_id): Path<Uuid>,
) -> Result<Json<ReadStateResponse>, HTTPError> {
state.repositories.channel.get_by_id(channel_id).await?.ok_or(HTTPError::NotFound)?;
let read_state = state.repositories.read_state.get(channel_id, user.id).await?;
let unread_count = state
.repositories
.read_state
.unread_counts(&[channel_id], user.id)
.await?
.get(&channel_id)
.copied()
.unwrap_or(0);
Ok(Json(ReadStateResponse {
channel_id,
last_read_message_id: read_state.as_ref().and_then(|value| value.last_read_message_id),
updated_at: read_state.map(|value| value.updated_at),
unread_count,
}))
}
#[utoipa::path(
put,
path = "/channels/{channel_id}/read-state",
request_body = SetReadStateRequest,
params(("channel_id" = Uuid, Path, description = "ID du canal")),
responses((status = 200, body = ReadStateResponse), (status = 400, description = "Message invalide"), (status = 404, description = "Canal non trouvé")),
tag = "Channels",
security(("bearerAuth" = []))
)]
pub async fn set_read_state(
user: CurrentUser,
State(state): State<AppState>,
Path(channel_id): Path<Uuid>,
Json(payload): Json<SetReadStateRequest>,
) -> Result<Json<ReadStateResponse>, HTTPError> {
state.repositories.channel.get_by_id(channel_id).await?.ok_or(HTTPError::NotFound)?;
if let Some(message_id) = payload.last_read_message_id {
let message = state
.repositories
.message
.get_by_id(message_id)
.await?
.ok_or(HTTPError::BadRequest("Message not found".to_string()))?;
if message.channel_id != channel_id {
return Err(HTTPError::BadRequest(
"Message does not belong to this channel".to_string(),
));
}
}
let read_state = state
.repositories
.read_state
.set(channel_id, user.id, payload.last_read_message_id)
.await?;
let unread_count = state
.repositories
.read_state
.unread_counts(&[channel_id], user.id)
.await?
.get(&channel_id)
.copied()
.unwrap_or(0);
Ok(Json(ReadStateResponse {
channel_id,
last_read_message_id: read_state.last_read_message_id,
updated_at: Some(read_state.updated_at),
unread_count,
}))
}
/// Récupère un channel par son ID
#[utoipa::path(
get,
+1
View File
@@ -23,6 +23,7 @@ pub fn channel_model_to_channel_response_with_permission(
name: model.name,
created_at: model.created_at,
updated_at: model.updated_at,
unread_count: None,
permission,
}
}
+4
View File
@@ -27,4 +27,8 @@ pub fn router() -> Router<AppState> {
.put(handlers::set_role_permission)
.delete(handlers::remove_role_permission),
)
.route(
"/channels/{channel_id}/read-state",
get(handlers::get_read_state).put(handlers::set_read_state),
)
}
+2
View File
@@ -60,6 +60,8 @@ use utoipa::{Modify, OpenApi};
crate::domain::dto::channel::ChannelResponse,
crate::domain::dto::channel::CreateChannelRequest,
crate::domain::dto::channel::UpdateChannelRequest,
crate::domain::dto::channel::ReadStateResponse,
crate::domain::dto::channel::SetReadStateRequest,
crate::domain::dto::role::RoleResponse,
crate::domain::dto::role::CreateRoleRequest,
crate::domain::dto::role::UpdateRoleRequest,
+15 -1
View File
@@ -43,16 +43,29 @@ async fn require_server_permission(
(status = 200, description = "Liste des serveurs récupérée avec succès", body = [ServerResponse]),
(status = 500, description = "Erreur interne du serveur")
),
security(("bearerAuth" = [])),
tag = "Servers"
)]
pub async fn get_all(
user: CurrentUser,
State(state): State<AppState>,
) -> Result<Json<Vec<ServerResponse>>, HTTPError> {
let servers = state.repositories.server.get_all().await?;
let unread_counts = state
.repositories
.read_state
.unread_counts_by_server(user.id)
.await?;
Ok(Json(
servers
.into_iter()
.map(mapper::server_model_to_server_response)
.map(|server| {
let server_id = server.id;
mapper::server_model_to_server_response_with_unread_count(
server,
unread_counts.get(&server_id).copied().unwrap_or(0),
)
})
.collect(),
))
}
@@ -456,5 +469,6 @@ pub async fn get_tree(
tree.orders,
tree.channels,
tree.categories,
tree.unread_counts,
)))
}
+17 -2
View File
@@ -17,9 +17,19 @@ pub fn server_model_to_server_response(model: server::Model) -> ServerResponse {
is_default: model.is_default,
created_at: model.created_at,
updated_at: model.updated_at,
unread_count: None,
}
}
pub fn server_model_to_server_response_with_unread_count(
model: server::Model,
unread_count: u64,
) -> ServerResponse {
let mut response = server_model_to_server_response(model);
response.unread_count = Some(unread_count);
response
}
pub fn create_request_to_am(req: CreateServerRequest) -> server::ActiveModel {
server::ActiveModel {
id: Set(Uuid::new_v4()),
@@ -66,6 +76,7 @@ pub fn build_server_tree(
orders: Vec<server_item_order::Model>,
channels: Vec<ChannelWithPermissions>,
categories: Vec<CategoryWithPermissions>,
unread_counts: HashMap<Uuid, u64>,
) -> ServerTreeResponse {
let order_map: HashMap<(Option<Uuid>, Uuid), i64> = orders
.into_iter()
@@ -119,7 +130,9 @@ pub fn build_server_tree(
.into_iter()
.map(|c| {
let chan_perm_bits = c.permissions.map(|p| p.bits()).unwrap_or(0);
channel_model_to_channel_response_with_permission(c.channel, Some(chan_perm_bits))
let mut response = channel_model_to_channel_response_with_permission(c.channel, Some(chan_perm_bits));
response.unread_count = Some(*unread_counts.get(&response.id).unwrap_or(&0));
response
})
.collect();
@@ -135,10 +148,11 @@ pub fn build_server_tree(
.copied()
.unwrap_or(i64::MAX);
let chan_perm_bits = chan_with_perm.permissions.map(|p| p.bits()).unwrap_or(0);
let chan_response = channel_model_to_channel_response_with_permission(
let mut chan_response = channel_model_to_channel_response_with_permission(
chan_with_perm.channel,
Some(chan_perm_bits),
);
chan_response.unread_count = Some(*unread_counts.get(&chan_response.id).unwrap_or(&0));
root_items.push((
ServerExplorerItemResponse::Channel(chan_response),
order_key,
@@ -232,6 +246,7 @@ mod tests {
channel(second_id, Some(category_id), "first"),
],
vec![category],
HashMap::new(),
);
let ServerExplorerItemResponse::Category(_, channels) = &response.items[0] else {