cards/server/src/lib.rs

78 lines
1.9 KiB
Rust
Raw Normal View History

2024-08-05 01:55:05 -04:00
#![feature(if_let_guard)]
2024-08-12 15:10:48 -04:00
use crate::game_handler::*;
2024-08-04 18:14:10 -04:00
use anyhow::{Context, Result};
use axum::extract::ws::Message;
2024-08-15 01:56:11 -04:00
use game_handler::*;
2024-08-04 18:14:10 -04:00
use lib::*;
use std::{
2024-08-05 00:08:29 -04:00
collections::{HashMap, HashSet},
2024-08-12 17:14:27 -04:00
fs::File,
2024-08-04 18:14:10 -04:00
io::{BufRead, BufReader},
net::SocketAddr,
sync::{Arc, RwLock},
};
use tokio::sync::mpsc::Sender;
use tokio::sync::{broadcast, mpsc};
2024-08-15 01:56:11 -04:00
use user_handler::*;
2024-08-11 19:51:30 -04:00
use uuid::Uuid;
2024-08-08 05:29:32 -04:00
pub mod game_handler;
pub mod message_handler;
2024-08-07 05:30:30 -04:00
pub mod user_handler;
pub mod websocket;
/// User
#[derive(Debug)]
pub struct User {
2024-08-20 22:25:39 -04:00
pub uuid: String,
pub name: String,
pub tx: Sender<String>,
}
impl User {
/// Create a new user object from incoming data
pub fn new(name: String, tx: Sender<String>) -> User {
2024-08-11 19:51:30 -04:00
User {
2024-08-20 22:25:39 -04:00
uuid: Uuid::now_v7().to_string(),
2024-08-11 19:51:30 -04:00
name,
tx,
}
}
pub fn change_name(&mut self, new_name: String) {
self.name = new_name;
}
}
2024-08-04 18:14:10 -04:00
/// Parse name list
pub fn load_names(path: &str) -> Result<Vec<String>> {
let f = File::open(path).with_context(|| format!("Invalid names path: \"{}\"", path))?;
let f = BufReader::new(f);
let mut buf = vec![];
for line in f.lines() {
buf.push(line?)
}
Ok(buf)
}
// Our shared state
pub struct AppState {
2024-08-20 22:25:39 -04:00
pub white_cards_by_id: HashMap<String, Arc<CardWhiteWithID>>,
pub broadcast_tx: broadcast::Sender<String>,
pub users_tx: mpsc::Sender<UserHandlerMessage>,
pub messages_tx: mpsc::Sender<(SocketAddr, Message)>,
2024-08-09 01:21:04 -04:00
pub games_tx: mpsc::Sender<GameHandlerMessage>,
pub first_names: Vec<String>,
pub last_names: Vec<String>,
2024-08-05 00:08:29 -04:00
pub reserved_names: RwLock<HashSet<String>>,
2024-08-20 22:25:39 -04:00
pub users_by_id: RwLock<HashMap<String, Arc<RwLock<User>>>>,
2024-08-04 18:14:10 -04:00
pub online_users: RwLock<HashMap<SocketAddr, Arc<RwLock<User>>>>,
pub offline_users: RwLock<HashMap<String, Arc<RwLock<User>>>>,
pub packs: CardPacks,
pub packs_meta: CardPacksMeta,
2024-08-09 01:21:04 -04:00
pub games: RwLock<HashMap<String, Arc<RwLock<Game>>>>,
2024-08-04 18:14:10 -04:00
}