Did a bit of polishing up
This commit is contained in:
+28
-20
@@ -1,40 +1,48 @@
|
||||
use warp::Filter;
|
||||
use std::{
|
||||
thread,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use crate::config;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::mpsc::*;
|
||||
use tokio::sync::RwLock;
|
||||
use crate::api;
|
||||
use warp::Filter;
|
||||
use crate::
|
||||
{
|
||||
Arc,
|
||||
Mutex,
|
||||
config,
|
||||
mpsc::Sender,
|
||||
info,
|
||||
warn,
|
||||
debug,
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct Data_to_send {
|
||||
pub struct DataToSend {
|
||||
pub action_type: String,
|
||||
pub content: String,
|
||||
pub character: String,
|
||||
}
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct Data_to_receive {
|
||||
pub response: String,
|
||||
}
|
||||
|
||||
pub async fn api_process(data_to_send: Arc<Mutex<Data_to_send>>, tx: Sender<u8>)
|
||||
// Async function that runs the api server in the background.
|
||||
// Waits for the client to load it, at which point it sends a 1 over
|
||||
// tx to allow the program executor to move onto the next bit of code
|
||||
pub async fn api_process(data_to_send: Arc<Mutex<DataToSend>>, tx: Sender<u8>)
|
||||
{
|
||||
// This data must be passed through to the api route in order to be used
|
||||
let data_filter = warp::any().map(move || Arc::clone(&data_to_send));
|
||||
let tx_filter = warp::any().map(move || tx.clone());
|
||||
println!("Running server");
|
||||
|
||||
debug!("Running server");
|
||||
|
||||
// The server route is loaded at address:port/happening
|
||||
let route = warp::path("happening")
|
||||
.and(warp::get())
|
||||
.and(data_filter)
|
||||
.and(tx_filter)
|
||||
.map(|state: Arc<Mutex<Data_to_send>>, tx_handle: Sender<u8>| {
|
||||
println!("GET: {:?}", state);
|
||||
// Perform this code on a GET request
|
||||
.map(|state: Arc<Mutex<DataToSend>>, tx_handle: Sender<u8>| {
|
||||
info!("GET: {:?}", state);
|
||||
let reply = state.as_ref();
|
||||
tx_handle.send(1);
|
||||
warp::reply::json(&reply)
|
||||
let _ = tx_handle.send(1);
|
||||
warp::reply::json(&reply) // Send the reply data (data_to_send formatted as JSON)
|
||||
}).boxed();
|
||||
|
||||
// Start the server
|
||||
warp::serve(route)
|
||||
.run(([127, 0, 0, 1],config::API_PORT))
|
||||
.await;
|
||||
|
||||
+14
-10
@@ -1,14 +1,16 @@
|
||||
use std::
|
||||
{
|
||||
fs,
|
||||
thread,
|
||||
collections::HashMap,
|
||||
sync::{Arc, Mutex, mpsc},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::runtime::Runtime;
|
||||
use tokio::task;
|
||||
use warp::Filter;
|
||||
use log::
|
||||
{
|
||||
info,
|
||||
trace,
|
||||
warn,
|
||||
debug,
|
||||
};
|
||||
|
||||
mod parsing;
|
||||
mod character;
|
||||
@@ -16,9 +18,11 @@ mod config;
|
||||
mod api;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
async fn main()
|
||||
{
|
||||
env_logger::init();
|
||||
let (tx,rx) = mpsc::channel();
|
||||
let mut data_to_send = Arc::new(Mutex::new(api::Data_to_send
|
||||
let data_to_send = Arc::new(Mutex::new(api::DataToSend
|
||||
{
|
||||
action_type: "initialise".to_string(),
|
||||
content: "".to_string(),
|
||||
@@ -32,7 +36,7 @@ async fn main() {
|
||||
async move {
|
||||
api::api_process(data, tx_clone).await;
|
||||
});
|
||||
println!("and continue");
|
||||
debug!("and continue");
|
||||
let mut characters = HashMap::<String, character::Character>::new();
|
||||
let file_contents: String = fs::read_to_string("stories/story.ha").unwrap();
|
||||
// Split the file contents into tokens
|
||||
@@ -43,7 +47,7 @@ async fn main() {
|
||||
let data_clone = Arc::clone(&data_to_send);
|
||||
match parsing::token_parse(&tokens, &mut characters, data_clone, &rx).await
|
||||
{
|
||||
Ok(()) => println!("Program exited successfully"),
|
||||
Err(error) => println!("{}", error),
|
||||
Ok(()) => info!("Program exited successfully"),
|
||||
Err(error) => eprintln!("{}", error),
|
||||
}
|
||||
}
|
||||
|
||||
+71
-67
@@ -1,19 +1,29 @@
|
||||
use std::collections::HashMap;
|
||||
use crate::character;
|
||||
use crate::api;
|
||||
use crate::mpsc::*;
|
||||
use std::{thread};
|
||||
use std::sync::{Arc,Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use std::thread;
|
||||
mod strings;
|
||||
use crate::
|
||||
{
|
||||
// Internal code
|
||||
character,
|
||||
api,
|
||||
|
||||
// Libraries
|
||||
mpsc::Receiver,
|
||||
Arc,
|
||||
Mutex,
|
||||
info,
|
||||
warn,
|
||||
debug,
|
||||
};
|
||||
|
||||
|
||||
// Parse the tokens in a file
|
||||
// Returns success or an error string
|
||||
pub async fn token_parse(
|
||||
tokens: &Vec<&str>,
|
||||
mut characters: &mut HashMap::<String, character::Character>,
|
||||
data_to_send: Arc<Mutex<api::Data_to_send>>,
|
||||
data_to_send: Arc<Mutex<api::DataToSend>>,
|
||||
rx: &Receiver<u8>,
|
||||
) -> Result<(),String>
|
||||
{
|
||||
@@ -21,44 +31,41 @@ pub async fn token_parse(
|
||||
// Run an infinite loop
|
||||
loop
|
||||
{
|
||||
match rx.try_recv()
|
||||
// If the client hasn't responded then continue (after a short pause)
|
||||
if rx.try_recv().is_err()
|
||||
{
|
||||
Ok(_) =>
|
||||
{
|
||||
match tokens.get(index) {
|
||||
Some(token) => {
|
||||
// The instructions are related to characters
|
||||
if token.chars().next().unwrap() == '@'
|
||||
{
|
||||
let character_name: String = token.chars().skip(1).collect();
|
||||
// If the character doesn't exist, then create it
|
||||
if ! characters.contains_key(&character_name)
|
||||
{
|
||||
let new_character = character::Character::new(character_name.clone());
|
||||
characters.insert(character_name.clone(),new_character);
|
||||
}
|
||||
println!("Doing something with a character: {}", character_name);
|
||||
// The index is incremented to after the character's instructions
|
||||
index += match character_parse(index+1, &tokens, character_name, &mut characters, &data_to_send, &rx).await
|
||||
{
|
||||
Ok(increment) => {
|
||||
increment
|
||||
},
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
// Miscelleneous instructions
|
||||
if token.to_lowercase() == "end"
|
||||
{
|
||||
return Ok(()) // quit
|
||||
}
|
||||
},
|
||||
None => return Err(String::from("File reached termination point")),
|
||||
}
|
||||
index += 1;
|
||||
},
|
||||
Err(_) => thread::sleep(Duration::from_millis(4000)),
|
||||
thread::sleep(Duration::from_millis(300));
|
||||
continue
|
||||
}
|
||||
// Get the next token
|
||||
let token = tokens
|
||||
.get(index)
|
||||
.ok_or_else(|| "File reached termination point".to_string())?;
|
||||
|
||||
// The instructions are related to characters
|
||||
if token.starts_with('@')
|
||||
{
|
||||
let character_name: String = token.chars().skip(1).collect();
|
||||
// If the character doesn't exist, then create it
|
||||
if ! characters.contains_key(&character_name)
|
||||
{
|
||||
let new_character = character::Character::new(character_name.clone());
|
||||
characters.insert(character_name.clone(),new_character);
|
||||
}
|
||||
println!("Doing something with a character: {}", character_name);
|
||||
// The index is incremented to after the character's instructions
|
||||
index += match character_parse(index+1, &tokens, character_name, &mut characters, &data_to_send, &rx).await
|
||||
{
|
||||
Ok(increment) => increment,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
// Miscelleneous instructions
|
||||
if token.to_lowercase() == "end"
|
||||
{
|
||||
return Ok(()) // quit
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
// Parsing character related instructions
|
||||
@@ -68,7 +75,7 @@ async fn character_parse
|
||||
tokens: &Vec<&str>,
|
||||
character_name: String,
|
||||
characters: &mut HashMap::<String, character::Character>,
|
||||
data_to_send: &Arc<Mutex<api::Data_to_send>>,
|
||||
data_to_send: &Arc<Mutex<api::DataToSend>>,
|
||||
rx: &Receiver<u8>,
|
||||
) -> Result<usize,String>
|
||||
{
|
||||
@@ -76,35 +83,32 @@ async fn character_parse
|
||||
loop
|
||||
{
|
||||
// Ensure the index is valid (the index is not beyond the vector)
|
||||
let _ = match tokens.get(sum_index)
|
||||
let token = tokens
|
||||
.get(sum_index)
|
||||
.ok_or_else(|| "File reached termination point".to_string())?;
|
||||
match token.to_lowercase().as_str()
|
||||
{
|
||||
Some(token) => {
|
||||
match token.to_lowercase().as_str()
|
||||
// The character is saying something, so grab the text and pass it
|
||||
// to the client
|
||||
"says" =>
|
||||
{
|
||||
match strings::extract_quoted(&tokens[sum_index+1..]) // TODO increment to after the string
|
||||
{
|
||||
// The character is saying something, so grab the text and pass it
|
||||
// to the client
|
||||
"says" =>
|
||||
Some(output_string) =>
|
||||
{
|
||||
match strings::extract_quoted(&tokens[sum_index+1..])
|
||||
{
|
||||
Some(output_string) =>
|
||||
{
|
||||
println!("{}", output_string);
|
||||
let mut data = data_to_send.lock().unwrap();
|
||||
data.action_type = String::from("output");
|
||||
data.content = output_string;
|
||||
data.character = character_name.clone();
|
||||
},
|
||||
None => return Err(String::from("Unable to read string")),
|
||||
}
|
||||
debug!("{}", output_string);
|
||||
let mut data = data_to_send.lock().unwrap();
|
||||
data.action_type = String::from("output");
|
||||
data.content = output_string;
|
||||
data.character = character_name.clone();
|
||||
},
|
||||
// Catch all condition, if the instruction is unrecognised as a
|
||||
// character command
|
||||
_ => return Err(String::from("Invalid command")),
|
||||
None => return Err(String::from("Unable to read string")),
|
||||
}
|
||||
},
|
||||
None => return Err(String::from("File reached termination point"))
|
||||
};
|
||||
// Catch all condition, if the instruction is unrecognised as a
|
||||
// character command
|
||||
_ => return Err(String::from(format!("Invalid command: {}", token))),
|
||||
}
|
||||
sum_index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
@@ -1,8 +1,7 @@
|
||||
pub fn extract_quoted(parts: &[&str]) -> Option<String> {
|
||||
pub fn extract_quoted(parts: &[&str]) -> Option<String> { // TODO also return a number to increment by
|
||||
let mut vec_string = Vec::new();
|
||||
for part in parts
|
||||
{
|
||||
println!("{}",part);
|
||||
if part.chars().next_back().unwrap() == '"'
|
||||
{
|
||||
vec_string.push(*part);
|
||||
|
||||
Reference in New Issue
Block a user