botserver/src/session/mod.rs

85 lines
2.2 KiB
Rust
Raw Normal View History

2025-10-11 20:41:52 -03:00
use diesel::PgConnection;
use log::info;
use redis::Client;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::error::Error;
2025-10-06 10:30:17 -03:00
use std::sync::Arc;
use uuid::Uuid;
2025-10-11 20:41:52 -03:00
#[derive(Clone, Serialize, Deserialize)]
pub struct UserSession {
pub id: Uuid,
pub user_id: Option<Uuid>,
pub data: String,
}
2025-10-06 10:30:17 -03:00
pub struct SessionManager {
2025-10-11 20:41:52 -03:00
sessions: HashMap<Uuid, UserSession>,
waiting_for_input: HashSet<Uuid>,
redis: Option<Arc<Client>>,
2025-10-06 10:30:17 -03:00
}
impl SessionManager {
2025-10-11 20:41:52 -03:00
pub fn new(_conn: PgConnection, redis_client: Option<Arc<Client>>) -> Self {
info!("Initializing SessionManager");
SessionManager {
sessions: HashMap::new(),
waiting_for_input: HashSet::new(),
redis: redis_client,
2025-10-06 10:30:17 -03:00
}
}
2025-10-11 20:41:52 -03:00
pub fn provide_input(
2025-10-11 12:29:03 -03:00
&mut self,
2025-10-06 10:30:17 -03:00
session_id: Uuid,
2025-10-11 20:41:52 -03:00
input: String,
) -> Result<(), Box<dyn Error + Send + Sync>> {
info!(
"SessionManager.provide_input called for session {}",
session_id
2025-10-11 12:29:03 -03:00
);
2025-10-11 20:41:52 -03:00
if let Some(sess) = self.sessions.get_mut(&session_id) {
sess.data = input;
} else {
let sess = UserSession {
id: session_id,
user_id: None,
data: input,
};
self.sessions.insert(session_id, sess);
2025-10-06 10:30:17 -03:00
}
2025-10-11 20:41:52 -03:00
self.waiting_for_input.remove(&session_id);
2025-10-06 10:30:17 -03:00
Ok(())
}
2025-10-11 20:41:52 -03:00
pub fn is_waiting_for_input(&self, session_id: &Uuid) -> bool {
self.waiting_for_input.contains(session_id)
2025-10-06 10:30:17 -03:00
}
2025-10-11 20:41:52 -03:00
pub fn create_session(&mut self) -> Uuid {
let id = Uuid::new_v4();
let sess = UserSession {
id,
user_id: None,
data: String::new(),
};
self.sessions.insert(id, sess);
info!("Created session {}", id);
id
2025-10-06 10:30:17 -03:00
}
2025-10-11 20:41:52 -03:00
pub fn mark_waiting(&mut self, session_id: Uuid) {
self.waiting_for_input.insert(session_id);
info!("Session {} marked as waiting for input", session_id);
2025-10-06 10:30:17 -03:00
}
2025-10-11 20:41:52 -03:00
pub fn get_session(&self, session_id: &Uuid) -> Option<UserSession> {
self.sessions.get(session_id).cloned()
2025-10-06 10:30:17 -03:00
}
2025-10-11 20:41:52 -03:00
pub fn list_sessions(&self) -> Vec<UserSession> {
self.sessions.values().cloned().collect()
2025-10-06 10:30:17 -03:00
}
}