Skip to content

Commit

Permalink
feat(platform): add chat history
Browse files Browse the repository at this point in the history
  • Loading branch information
lennartkloock committed Jan 10, 2024
1 parent 9818b0f commit 6972ae0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
24 changes: 18 additions & 6 deletions platform/api/src/api/v1/gql/subscription/chat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::api::v1::gql::error::Result;
use crate::api::v1::gql::ext::ContextExt;
use crate::api::v1::gql::models::chat_message::{ChatMessage, MessageType};
use crate::api::v1::gql::models::ulid::GqlUlid;
use crate::database;
use crate::global::ApiGlobal;
use crate::subscription::SubscriptionTopic;

Expand Down Expand Up @@ -41,20 +42,31 @@ impl<G: ApiGlobal> ChatSubscription<G> {
};

// TODO: check if user is allowed to read this chat
// let channel = global
// .user_by_id_loader
// .load_one(channel_id.into())
// .await
// .map_err_gql("failed to fetch user")?
// .ok_or(GqlError::NotFound.with_message("user not found"))?;

let mut message_stream = global
.subscription_manager()
.subscribe(SubscriptionTopic::ChannelChatMessages(channel_id.to_ulid()))
.await
.map_err_gql("failed to subscribe to chat messages")?;

// load old messages not older than 10 minutes, max 100 messages
let not_older_than = chrono::Utc::now() - chrono::Duration::minutes(10);
let not_older_than = ulid::Ulid::from_parts(not_older_than.timestamp() as u64, u128::MAX);
let messages: Vec<database::ChatMessage> = sqlx::query_as(
"SELECT * FROM chat_messages WHERE channel_id = $1 AND deleted_at IS NULL AND id >= $2 ORDER BY id LIMIT 100",
)
.bind(common::database::Ulid::from(channel_id.to_ulid()))
.bind(common::database::Ulid::from(not_older_than))
.fetch_all(global.db().as_ref())
.await
.map_err_gql("failed to fetch chat messages")?;

dbg!(&messages);

Ok(stream!({
for message in messages {
yield Ok(message.into());
}
yield Ok(welcome_message);
while let Ok(message) = message_stream.recv().await {
let event = pb::scuffle::platform::internal::events::ChatMessage::decode(message.payload)
Expand Down
6 changes: 4 additions & 2 deletions platform/api/src/database/chat_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ use common::database::Ulid;
pub struct ChatMessage {
/// The unique identifier for the chat message.
pub id: Ulid,
/// The unique identifier for the chat room which owns the message.
pub channel_id: Ulid,
/// The unique identifier for the user who sent the message.
pub user_id: Ulid,
/// The unique identifier for the chat room which owns the message.
pub channel_id: Ulid,
/// The content of the message.
pub content: String,
/// The time the message was deleted.
pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,
}

impl ChatMessage {
Expand Down

0 comments on commit 6972ae0

Please sign in to comment.