Set up a database and serve character sheets from it #277

Merged
savanni merged 7 commits from visions-database into main 2024-11-30 23:56:21 +00:00
4 changed files with 80 additions and 34 deletions
Showing only changes of commit 995390ae4b - Show all commits

View File

@ -1,14 +1,14 @@
use std::{ use std::{collections::HashMap, sync::Arc};
collections::HashMap,
sync::{Arc, RwLock},
};
use async_std::sync::RwLock;
use mime::Mime; use mime::Mime;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use uuid::Uuid; use uuid::Uuid;
use crate::{ use crate::{
asset_db::{self, AssetId, Assets}, database::Database, types::{AppError, Message, Tabletop, RGB} asset_db::{self, AssetId, Assets},
database::{CharacterId, Database},
types::{AppError, Message, Tabletop, RGB},
}; };
const DEFAULT_BACKGROUND_COLOR: RGB = RGB { const DEFAULT_BACKGROUND_COLOR: RGB = RGB {
@ -50,8 +50,8 @@ impl Core {
}))) })))
} }
pub fn register_client(&self) -> String { pub async fn register_client(&self) -> String {
let mut state = self.0.write().unwrap(); let mut state = self.0.write().await;
let uuid = Uuid::new_v4().simple().to_string(); let uuid = Uuid::new_v4().simple().to_string();
let client = WebsocketClient { sender: None }; let client = WebsocketClient { sender: None };
@ -60,13 +60,13 @@ impl Core {
uuid uuid
} }
pub fn unregister_client(&self, client_id: String) { pub async fn unregister_client(&self, client_id: String) {
let mut state = self.0.write().unwrap(); let mut state = self.0.write().await;
let _ = state.clients.remove(&client_id); let _ = state.clients.remove(&client_id);
} }
pub fn connect_client(&self, client_id: String) -> UnboundedReceiver<Message> { pub async fn connect_client(&self, client_id: String) -> UnboundedReceiver<Message> {
let mut state = self.0.write().unwrap(); let mut state = self.0.write().await;
match state.clients.get_mut(&client_id) { match state.clients.get_mut(&client_id) {
Some(client) => { Some(client) => {
@ -80,14 +80,14 @@ impl Core {
} }
} }
pub fn tabletop(&self) -> Tabletop { pub async fn tabletop(&self) -> Tabletop {
self.0.read().unwrap().tabletop.clone() self.0.read().await.tabletop.clone()
} }
pub async fn get_asset(&self, asset_id: AssetId) -> Result<(Mime, Vec<u8>), AppError> { pub async fn get_asset(&self, asset_id: AssetId) -> Result<(Mime, Vec<u8>), AppError> {
self.0 self.0
.read() .read()
.unwrap() .await
.asset_store .asset_store
.get(asset_id.clone()) .get(asset_id.clone())
.map_err(|err| match err { .map_err(|err| match err {
@ -97,24 +97,24 @@ impl Core {
}) })
} }
pub fn available_images(&self) -> Vec<AssetId> { pub async fn available_images(&self) -> Vec<AssetId> {
self.0 self.0
.read() .read()
.unwrap() .await
.asset_store .asset_store
.assets() .assets()
.filter_map(|(asset_id, value)| { .filter_map(
match mime_guess::from_path(&value).first() { |(asset_id, value)| match mime_guess::from_path(&value).first() {
Some(mime) if mime.type_() == mime::IMAGE => Some(asset_id.clone()), Some(mime) if mime.type_() == mime::IMAGE => Some(asset_id.clone()),
_ => None, _ => None,
} },
}) )
.collect() .collect()
} }
pub fn set_background_image(&self, asset: AssetId) -> Result<(), AppError> { pub async fn set_background_image(&self, asset: AssetId) -> Result<(), AppError> {
let tabletop = { let tabletop = {
let mut state = self.0.write().unwrap(); let mut state = self.0.write().await;
state.tabletop.background_image = Some(asset.clone()); state.tabletop.background_image = Some(asset.clone());
state.tabletop.clone() state.tabletop.clone()
}; };
@ -122,8 +122,23 @@ impl Core {
Ok(()) Ok(())
} }
pub fn publish(&self, message: Message) { pub async fn get_charsheet(
let state = self.0.read().unwrap(); &self,
id: CharacterId,
) -> Result<Option<serde_json::Value>, AppError> {
Ok(self
.0
.write()
.await
.db
.charsheet(id)
.await
.unwrap()
.map(|cr| cr.data))
}
pub async fn publish(&self, message: Message) {
let state = self.0.read().await;
state.clients.values().for_each(|client| { state.clients.values().for_each(|client| {
if let Some(ref sender) = client.sender { if let Some(ref sender) = client.sender {
@ -141,7 +156,10 @@ mod test {
use cool_asserts::assert_matches; use cool_asserts::assert_matches;
use crate::{asset_db::mocks::MemoryAssets, database::{DbConn, DiskDb}}; use crate::{
asset_db::mocks::MemoryAssets,
database::{DbConn, DiskDb},
};
fn test_core() -> Core { fn test_core() -> Core {
let assets = MemoryAssets::new(vec![ let assets = MemoryAssets::new(vec![

View File

@ -77,7 +77,7 @@ impl From<String> for CharacterId {
pub struct CharsheetRow { pub struct CharsheetRow {
id: String, id: String,
gametype: String, gametype: String,
data: serde_json::Value, pub data: serde_json::Value,
} }
#[async_trait] #[async_trait]
@ -172,7 +172,7 @@ impl DiskDb {
} }
} }
async fn db_handler(db: DiskDb, mut requestor: Receiver<DatabaseRequest>) { async fn db_handler(db: DiskDb, requestor: Receiver<DatabaseRequest>) {
println!("Starting db_handler"); println!("Starting db_handler");
while let Ok(DatabaseRequest { tx, req }) = requestor.recv().await { while let Ok(DatabaseRequest { tx, req }) = requestor.recv().await {
println!("Request received: {:?}", req); println!("Request received: {:?}", req);

View File

@ -4,7 +4,7 @@ use futures::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use warp::{http::Response, http::StatusCode, reply::Reply, ws::Message}; use warp::{http::Response, http::StatusCode, reply::Reply, ws::Message};
use crate::{asset_db::AssetId, core::Core, types::AppError}; use crate::{asset_db::AssetId, core::Core, database::CharacterId, types::AppError};
/* /*
pub async fn handle_auth( pub async fn handle_auth(
@ -62,6 +62,7 @@ pub async fn handle_available_images(core: Core) -> impl Reply {
handler(async move { handler(async move {
let image_paths: Vec<String> = core let image_paths: Vec<String> = core
.available_images() .available_images()
.await
.into_iter() .into_iter()
.map(|path| format!("{}", path.as_str())) .map(|path| format!("{}", path.as_str()))
.collect(); .collect();
@ -85,7 +86,7 @@ pub struct RegisterResponse {
pub async fn handle_register_client(core: Core, _request: RegisterRequest) -> impl Reply { pub async fn handle_register_client(core: Core, _request: RegisterRequest) -> impl Reply {
handler(async move { handler(async move {
let client_id = core.register_client(); let client_id = core.register_client().await;
Ok(Response::builder() Ok(Response::builder()
.header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Origin", "*")
@ -105,7 +106,10 @@ pub async fn handle_unregister_client(core: Core, client_id: String) -> impl Rep
handler(async move { handler(async move {
core.unregister_client(client_id); core.unregister_client(client_id);
Ok(Response::builder().status(StatusCode::NO_CONTENT).body(vec![]).unwrap()) Ok(Response::builder()
.status(StatusCode::NO_CONTENT)
.body(vec![])
.unwrap())
}) })
.await .await
} }
@ -120,10 +124,10 @@ pub async fn handle_connect_websocket(
let core = core.clone(); let core = core.clone();
async move { async move {
let (mut ws_sender, _) = socket.split(); let (mut ws_sender, _) = socket.split();
let mut receiver = core.connect_client(client_id.clone()); let mut receiver = core.connect_client(client_id.clone()).await;
tokio::task::spawn(async move { tokio::task::spawn(async move {
let tabletop = core.tabletop(); let tabletop = core.tabletop().await;
let _ = ws_sender let _ = ws_sender
.send(Message::text( .send(Message::text(
serde_json::to_string(&crate::types::Message::UpdateTabletop(tabletop)) serde_json::to_string(&crate::types::Message::UpdateTabletop(tabletop))
@ -155,3 +159,20 @@ pub async fn handle_set_background_image(core: Core, image_name: String) -> impl
}) })
.await .await
} }
pub async fn handle_get_charsheet(core: Core, charid: String) -> impl Reply {
handler(async move {
let sheet = core.get_charsheet(CharacterId::from(charid)).await.unwrap();
match sheet {
Some(sheet) => Ok(Response::builder()
.body(serde_json::to_vec(&sheet).unwrap())
.unwrap()),
None => Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(vec![])
.unwrap()),
}
})
.await
}

View File

@ -8,8 +8,7 @@ use asset_db::{AssetId, FsAssets};
use authdb::AuthError; use authdb::AuthError;
use database::DbConn; use database::DbConn;
use handlers::{ use handlers::{
handle_available_images, handle_connect_websocket, handle_file, handle_register_client, handle_available_images, handle_connect_websocket, handle_file, handle_get_charsheet, handle_register_client, handle_set_background_image, handle_unregister_client, RegisterRequest
handle_set_background_image, handle_unregister_client, RegisterRequest,
}; };
use warp::{ use warp::{
// header, // header,
@ -161,6 +160,13 @@ pub async fn main() {
}) })
.with(log); .with(log);
let route_get_charsheet = warp::path!("api" / "v1" / "charsheet" / String)
.and(warp::get())
.then({
let core = core.clone();
move |charid| handle_get_charsheet(core.clone(), charid)
});
let filter = route_register_client let filter = route_register_client
.or(route_unregister_client) .or(route_unregister_client)
.or(route_websocket) .or(route_websocket)
@ -168,6 +174,7 @@ pub async fn main() {
.or(route_available_images) .or(route_available_images)
.or(route_set_bg_image_options) .or(route_set_bg_image_options)
.or(route_set_bg_image) .or(route_set_bg_image)
.or(route_get_charsheet)
.recover(handle_rejection); .recover(handle_rejection);
let server = warp::serve(filter); let server = warp::serve(filter);