This commit is contained in:
Bartal Læarsson
2026-06-18 12:02:58 +01:00
parent df0a578207
commit f24da78970
9 changed files with 1250 additions and 96 deletions
+139 -53
View File
@@ -1,28 +1,28 @@
use axum::{
extract::{Path, State, Form},
extract::{ConnectInfo, Form, Path, State},
response::Html,
};
use chrono::Utc;
use std::sync::Arc;
use std::{net::SocketAddr, sync::Arc};
use uuid::Uuid;
use crate::{
models::{ChatSession, Message, MessageSender, SendMessageForm, NewSessionForm, SessionStatus},
state::AppState,
models::{ChatSession, Message, MessageSender, NewSessionForm, SendMessageForm, SessionStatus},
state::{AppState, MESSAGE_LIMIT_PER_WINDOW, SESSION_LIMIT_PER_WINDOW},
};
const MAX_MESSAGE_CHARS: usize = 1_000;
const MAX_NAME_CHARS: usize = 40;
fn render_message(msg: &Message) -> String {
let (bubble_class, label) = match msg.sender {
MessageSender::Customer => ("msg-customer", "You"),
MessageSender::Agent => ("msg-agent", "Support"),
MessageSender::User => ("msg-user", "You"),
MessageSender::Supporter => ("msg-supporter", "Support"),
MessageSender::System => ("msg-system", ""),
};
if msg.sender == MessageSender::System {
format!(
"<div class=\"msg-system-wrap\"><span class=\"msg-system-text\">{}</span></div>",
html_escape(&msg.content)
)
render_system_notice(&msg.content)
} else {
let time = msg.timestamp.format("%H:%M").to_string();
format!(
@@ -39,11 +39,34 @@ fn render_message(msg: &Message) -> String {
}
}
fn render_system_notice(content: &str) -> String {
format!(
"<div class=\"msg-system-wrap\"><span class=\"msg-system-text\">{}</span></div>",
html_escape(content)
)
}
fn html_escape(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
.replace('\'', "&#39;")
}
fn limit_key(kind: &str, addr: SocketAddr) -> String {
format!("{}:{}", kind, addr.ip())
}
fn clean_text(input: &str, max_chars: usize) -> Result<String, String> {
let trimmed = input.trim();
if trimmed.is_empty() {
return Ok(String::new());
}
if trimmed.chars().count() > max_chars {
return Err(format!("Please keep this under {max_chars} characters."));
}
Ok(trimmed.to_string())
}
/// GET /messages/:session_id
@@ -52,76 +75,119 @@ pub async fn get_messages(
State(state): State<Arc<AppState>>,
) -> Html<String> {
let Some(session) = state.sessions.get(&session_id) else {
return Html("<p class='error'>Session not found.</p>".to_string());
return Html(render_system_notice(
"Session not found. Chat history may have been cleared; please start a new chat.",
));
};
let html: String = session.messages.iter().map(render_message).collect();
Html(html)
}
/// POST /send/:session_id — customer sends a message
/// POST /send/:session_id — user sends a message
pub async fn send_message(
ConnectInfo(addr): ConnectInfo<SocketAddr>,
Path(session_id): Path<String>,
State(state): State<Arc<AppState>>,
Form(form): Form<SendMessageForm>,
) -> Html<String> {
let content = form.content.trim().to_string();
if state.is_rate_limited(limit_key("message", addr), MESSAGE_LIMIT_PER_WINDOW) {
return Html(render_system_notice(
"Too many messages from this network. Please wait until the 3-minute window resets.",
));
}
let content = match clean_text(&form.content, MAX_MESSAGE_CHARS) {
Ok(content) => content,
Err(message) => return Html(render_system_notice(&message)),
};
if content.is_empty() {
return Html(String::new());
}
let Some(mut session) = state.sessions.get_mut(&session_id) else {
return Html(render_system_notice(
"Session not found. Chat history may have been cleared; please start a new chat.",
));
};
let msg = Message {
id: Uuid::new_v4().to_string(),
session_id: session_id.clone(),
sender: MessageSender::Customer,
sender: MessageSender::User,
content,
timestamp: Utc::now(),
};
let rendered = render_message(&msg);
if let Some(mut session) = state.sessions.get_mut(&session_id) {
session.messages.push(msg);
if let Some(tx) = state.notifiers.get(&session_id) {
let _ = tx.send(session_id.clone());
}
let _ = state.agent_notifier.send(session_id.clone());
session.messages.push(msg);
if let Some(tx) = state.notifiers.get(&session_id) {
let _ = tx.send(session_id.clone());
}
let _ = state.supporter_notifier.send(session_id.clone());
Html(rendered)
}
/// POST /agent/send/:session_id — agent sends a message
pub async fn agent_send_message(
/// POST /supporter/send/:session_id — supporter sends a message
pub async fn supporter_send_message(
ConnectInfo(addr): ConnectInfo<SocketAddr>,
Path(session_id): Path<String>,
State(state): State<Arc<AppState>>,
Form(form): Form<SendMessageForm>,
) -> Html<String> {
let content = form.content.trim().to_string();
if state.is_rate_limited(limit_key("supporter-message", addr), MESSAGE_LIMIT_PER_WINDOW) {
return Html(render_system_notice(
"Too many messages from this network. Please wait until the 3-minute window resets.",
));
}
let content = match clean_text(&form.content, MAX_MESSAGE_CHARS) {
Ok(content) => content,
Err(message) => return Html(render_system_notice(&message)),
};
if content.is_empty() {
return Html(String::new());
}
let Some(mut session) = state.sessions.get_mut(&session_id) else {
return Html(render_system_notice(
"Session not found. Chat history may have been cleared.",
));
};
let msg = Message {
id: Uuid::new_v4().to_string(),
session_id: session_id.clone(),
sender: MessageSender::Agent,
sender: MessageSender::Supporter,
content,
timestamp: Utc::now(),
};
let rendered = render_message(&msg);
if let Some(mut session) = state.sessions.get_mut(&session_id) {
session.messages.push(msg);
session.status = SessionStatus::Active;
if let Some(tx) = state.notifiers.get(&session_id) {
let _ = tx.send(session_id.clone());
}
session.messages.push(msg);
session.status = SessionStatus::Active;
if let Some(tx) = state.notifiers.get(&session_id) {
let _ = tx.send(session_id.clone());
}
let _ = state.supporter_notifier.send(session_id.clone());
Html(rendered)
}
/// GET /sessions — session list for agent dashboard
pub async fn get_sessions(
State(state): State<Arc<AppState>>,
) -> Html<String> {
let mut sessions: Vec<_> = state.sessions
/// GET /sessions — session list for supporter dashboard
pub async fn get_sessions(State(state): State<Arc<AppState>>) -> Html<String> {
let mut sessions: Vec<_> = state
.sessions
.iter()
.filter(|s| s.status != SessionStatus::Closed)
.map(|s| (s.id.clone(), s.customer_name.clone(), s.status.clone(), s.messages.len()))
.map(|s| {
(
s.id.clone(),
s.user_name.clone(),
s.status.clone(),
s.messages.len(),
)
})
.collect();
sessions.sort_by(|a, b| a.0.cmp(&b.0));
@@ -134,22 +200,24 @@ pub async fn get_sessions(
for (id, name, status, count) in &sessions {
let status_class = match status {
SessionStatus::Waiting => "status-waiting",
SessionStatus::Active => "status-active",
SessionStatus::Closed => "status-closed",
SessionStatus::Active => "status-active",
SessionStatus::Closed => "status-closed",
};
let status_label = match status {
SessionStatus::Waiting => "Waiting",
SessionStatus::Active => "Active",
SessionStatus::Closed => "Closed",
SessionStatus::Active => "Active",
SessionStatus::Closed => "Closed",
};
let short_id = &id[..8];
let escaped_name = html_escape(name);
html.push_str(&format!(
"<button class=\"session-item\" \
hx-get=\"/messages/{id}\" \
hx-target=\"#agent-messages\" \
hx-target=\"#supporter-messages\" \
hx-swap=\"innerHTML\" \
onclick=\"document.querySelectorAll('.session-item').forEach(function(b){{b.classList.remove('selected')}}); this.classList.add('selected'); setActiveSession('{id}', '{escaped_name}')\">\
data-session-id=\"{id}\" \
data-session-name=\"{escaped_name}\" \
onclick=\"selectSession(this)\">\
<span class=\"session-name\">{escaped_name}</span>\
<span class=\"session-meta\">\
<span class=\"session-badge {status_class}\">{status_label}</span>\
@@ -162,43 +230,61 @@ pub async fn get_sessions(
Html(html)
}
/// POST /sessions/new — start a new customer session
/// POST /sessions/new — start a new user session
pub async fn new_session(
ConnectInfo(addr): ConnectInfo<SocketAddr>,
State(state): State<Arc<AppState>>,
Form(form): Form<NewSessionForm>,
) -> Html<String> {
let name = form.name.trim().to_string();
let name = if name.is_empty() { "Anonymous".to_string() } else { name };
if state.is_rate_limited(limit_key("session", addr), SESSION_LIMIT_PER_WINDOW) {
return Html(
"<script>alert('Too many new chats from this network. Please wait until the 3-minute window resets.');</script>"
.to_string(),
);
}
let name = match clean_text(&form.name, MAX_NAME_CHARS) {
Ok(name) if !name.is_empty() => name,
Ok(_) => "Anonymous".to_string(),
Err(message) => {
return Html(format!(
"<script>alert('{}');</script>",
html_escape(&message)
));
}
};
let session_id = Uuid::new_v4().to_string();
let short = session_id[..8].to_string();
let session = ChatSession::new(session_id.clone(), name.clone());
state.sessions.insert(session_id.clone(), session);
state.get_or_create_notifier(&session_id);
let _ = state.agent_notifier.send(session_id.clone());
let _ = state.supporter_notifier.send(session_id.clone());
// The response swaps out #start-form and fills #chat-container via OOB
// The response swaps out #start-form and fills #chat-container via OOB.
let html = format!(
"<div id=\"chat-container\" style=\"display:flex;flex-direction:column\" hx-swap-oob=\"true\">\
<div id=\"chat-header\">\
<span class=\"chat-status-dot active\"></span>\
<span>Support Chat</span>\
<span>Support chat</span>\
<span class=\"chat-session-id\">Session #{short}</span>\
</div>\
<div id=\"messages\" \
hx-get=\"/messages/{session_id}\" \
hx-trigger=\"load, every 2s\" \
hx-trigger=\"load, refresh, every 2s\" \
hx-swap=\"innerHTML\">\
</div>\
<div id=\"typing-indicator\" class=\"htmx-indicator\">\
<span class=\"typing-dot\"></span><span class=\"typing-dot\"></span><span class=\"typing-dot\"></span>\
<div id=\"peer-typing\" class=\"typing-bubble\" aria-live=\"polite\">\
<span class=\"typing-bubble-inner\" aria-label=\"Supporter is typing\">\
<span class=\"typing-dot\"></span><span class=\"typing-dot\"></span><span class=\"typing-dot\"></span>\
</span>\
</div>\
<form id=\"chat-form\" \
hx-post=\"/send/{session_id}\" \
hx-target=\"#messages\" \
hx-swap=\"beforeend\" \
hx-on=\"htmx:afterRequest: this.reset(); scrollMessages()\">\
<input type=\"text\" name=\"content\" placeholder=\"Type your message...\" autocomplete=\"off\" required />\
<input id=\"chat-input\" type=\"text\" name=\"content\" placeholder=\"Type your message...\" autocomplete=\"off\" maxlength=\"1000\" oninput=\"sendUserTyping()\" required />\
<button type=\"submit\">Send</button>\
</form>\
</div>\