From 8611273a89e6ffcb4c1da9dd600692920bd604fe Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sat, 8 May 2021 13:12:05 -0400 Subject: [PATCH] spawn command handler --- protos/storyteller-protos | 2 +- src/handlers/mod.rs | 3 +- src/handlers/spawn_handler.rs | 154 ++++++++++++++++++++++++ src/main.rs | 16 ++- src/proto_codegen/storyteller.unreal.rs | 8 +- src/protos.rs | 20 ++- 6 files changed, 193 insertions(+), 10 deletions(-) create mode 100644 src/handlers/spawn_handler.rs diff --git a/protos/storyteller-protos b/protos/storyteller-protos index faf4d85ac6..c61a069a6f 160000 --- a/protos/storyteller-protos +++ b/protos/storyteller-protos @@ -1 +1 @@ -Subproject commit faf4d85ac62186624d2c4921e42fec889f152e7a +Subproject commit c61a069a6ffcd6fdc15684e3086c48373a670fd0 diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs index 30b015c978..40c51bb58e 100644 --- a/src/handlers/mod.rs +++ b/src/handlers/mod.rs @@ -1 +1,2 @@ -pub mod coordinate_and_geocode_handler; \ No newline at end of file +pub mod coordinate_and_geocode_handler; +pub mod spawn_handler; \ No newline at end of file diff --git a/src/handlers/spawn_handler.rs b/src/handlers/spawn_handler.rs new file mode 100644 index 0000000000..5380aa23b5 --- /dev/null +++ b/src/handlers/spawn_handler.rs @@ -0,0 +1,154 @@ +use crate::AnyhowResult; +use crate::clients::redis_client::RedisClient; +use crate::dispatcher::TextCommandHandler; +use crate::inbound_proto_utils::{InboundEvent, InboundEventSource}; +use crate::protos::{protos, binary_encode_proto}; +use crate::text_chat_parsers::first_pass_command_parser::FirstPassParsedCommand; +use futures::executor::block_on; +use lazy_static::lazy_static; +use log::{info, warn, debug}; +use prost::Message; +use regex::Regex; +use std::sync::{RwLock, Arc, Mutex}; + +// TODO: maybe separate text command handling and data source concerns +// like this? Though maybe it's too early to optimize this. +pub struct SpawnHandler { + redis_client: Arc>, +} + +impl SpawnHandler { + pub fn new(redis_client: Arc>) -> Self { + Self { + redis_client, + } + } + + fn handle(&self, + spawn: SpawnCommand, + event: &InboundEvent, + event_source: &InboundEventSource) + -> AnyhowResult<()> { + + let mut unreal_proto = protos::UnrealEventPayloadV1::default(); + + // Payload + let mut spawn_proto = protos::SpawnCreatureRequest::default(); + spawn_proto.name_slug = spawn.spawn_slug; + + debug!("Payload Proto: {:?}", spawn_proto); + + unreal_proto.payload_type = protos::unreal_event_payload_v1::PayloadType::CesiumWarp as i32; + unreal_proto.payload_data = binary_encode_proto(spawn_proto)?; + unreal_proto.debug_message = "Hello from Rust!".to_string(); + + // Source data + match event_source { + InboundEventSource::Twitch(ref twitch_source) => { + let mut twitch_metadata = protos::TwitchMetadata::default(); + twitch_metadata.username = twitch_source.username.clone().unwrap_or("".to_string()); + twitch_metadata.user_id = twitch_source.user_id.clone().unwrap_or(0); + twitch_metadata.user_is_mod = twitch_source.user_is_mod.unwrap_or(false); + twitch_metadata.user_is_subscribed = twitch_source.user_is_subscribed.unwrap_or(false); + twitch_metadata.channel = twitch_source.channel.clone().unwrap_or("".to_string()); + + debug!("Source Proto: {:?}", twitch_metadata); + + unreal_proto.source_type = protos::unreal_event_payload_v1::SourceType::StTwitch as i32; + unreal_proto.source_data = binary_encode_proto(twitch_metadata)?; + } + } + + let publish_binary = binary_encode_proto(unreal_proto)?; + + match self.redis_client.lock() { + Ok(mut redis_client) => { + debug!("Publishing to Redis..."); + let future = redis_client.publish_bytes("unreal", &publish_binary); + block_on(future); + debug!("Published to redis"); + }, + Err(_) => {}, + } + + Ok(()) + } +} + +impl TextCommandHandler for SpawnHandler { + fn handle_text_command(&self, + command: &FirstPassParsedCommand, + event: &InboundEvent, + event_source: &InboundEventSource) + -> AnyhowResult<()> + { + let maybe_spawn_command = parse_spawn(&command.unparsed_arguments); + + debug!("Maybe spawn command: {:?}", maybe_spawn_command); + + if let Some(spawn) = maybe_spawn_command { + self.handle(spawn, event, event_source); + } + Ok(()) + } +} + +#[derive(Clone,Debug,PartialEq)] +pub struct SpawnCommand { + pub spawn_slug: String, + // TODO: Args in the future. +} + +pub fn parse_spawn(input: &str) -> Option { + lazy_static! { + static ref REGEX: Regex = + Regex::new(r"^\s*([\w\-]+)\s*$").expect("Regex should work"); + } + + let captures = match REGEX.captures(&input) { + None => return None, + Some(caps) => caps, + }; + + let maybe_capture = captures.get(1) + .map(|m| m.as_str()); + + + let capture = match maybe_capture { + None => return None, + Some(cap) => cap, + }; + + Some(SpawnCommand { + spawn_slug: capture.to_string(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use expectest::prelude::*; + + #[test] + fn failure_cases() { + expect!(parse_spawn("too many words")).to(be_none()); + expect!(parse_spawn("")).to(be_none()); + expect!(parse_spawn(" ")).to(be_none()); + } + + #[test] + fn single_word() { + expect!(parse_spawn("goomba")).to( + be_eq(Some(SpawnCommand { + spawn_slug: "goomba".to_string(), + }))); + } + + #[test] + fn hyphenated_word() { + expect!(parse_spawn("like-like")).to( + be_eq(Some(SpawnCommand { + spawn_slug: "like-like".to_string(), + }))); + } +} diff --git a/src/main.rs b/src/main.rs index b7f5befeb3..61b854f385 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,9 @@ +#![allow(dead_code)] +#![allow(unused_mut)] +#![allow(unused_imports)] +#![warn(unused_must_use)] +//#![allow(warnings)] + #[macro_use] extern crate lazy_static; #[macro_use] @@ -26,6 +32,7 @@ use crate::dispatcher::Dispatcher; use crate::handlers::coordinate_and_geocode_handler::CoordinateAndGeocodeHandler; use crate::secrets::Secrets; use std::sync::{Arc, Mutex}; +use crate::handlers::spawn_handler::SpawnHandler; pub type AnyhowResult = anyhow::Result; @@ -61,9 +68,12 @@ async fn main() -> anyhow::Result<()> { let redis_client = Arc::new(Mutex::new(redis_client)); - let coord_geo_handler = CoordinateAndGeocodeHandler::new(redis_client); - - dispatcher.add_text_command_handler("goto", Box::new(coord_geo_handler)); + dispatcher.add_text_command_handler( + "goto", + Box::new(CoordinateAndGeocodeHandler::new(redis_client.clone()))); + dispatcher.add_text_command_handler( + "spawn", + Box::new(SpawnHandler::new(redis_client.clone()))); let mut redis_pubsub_client = RedisSubscribeClient::new( &secrets.redis, diff --git a/src/proto_codegen/storyteller.unreal.rs b/src/proto_codegen/storyteller.unreal.rs index 4de6d92a23..bea0e28202 100644 --- a/src/proto_codegen/storyteller.unreal.rs +++ b/src/proto_codegen/storyteller.unreal.rs @@ -146,8 +146,8 @@ pub struct LevelWarpRequest { #[derive(Clone, PartialEq, ::prost::Message)] pub struct SpawnCreatureRequest { /// Required. Name of the creature. - #[prost(int64, tag="1")] - pub name_slug: i64, + #[prost(string, tag="1")] + pub name_slug: ::prost::alloc::string::String, } /// Do text to speech #[derive(Clone, PartialEq, ::prost::Message)] @@ -156,8 +156,8 @@ pub struct VocodesTtsRequest { #[prost(string, tag="1")] pub voice_slug: ::prost::alloc::string::String, /// Required. Text to speak. - #[prost(double, tag="2")] - pub text: f64, + #[prost(string, tag="2")] + pub text: ::prost::alloc::string::String, } // ============================== TWITTER EVENT PROTOS ============================== // diff --git a/src/protos.rs b/src/protos.rs index b8b426dacf..fab72b8edb 100644 --- a/src/protos.rs +++ b/src/protos.rs @@ -1,5 +1,23 @@ +use crate::AnyhowResult; +use anyhow::anyhow; + // Include the protos pub mod protos { include!("proto_codegen/storyteller.pubsub.rs"); include!("proto_codegen/storyteller.unreal.rs"); -} \ No newline at end of file +} + +// Binary encode a proto. +pub fn binary_encode_proto(proto: impl prost::Message) -> AnyhowResult> { + let mut buffer : Vec = Vec::with_capacity(proto.encoded_len()); + let encode_result = proto.encode(&mut buffer); + + match encode_result { + Err(e) => { + Err(anyhow!("Inner proto encode result: {:?}", e)) + } + Ok(_) => { + Ok(buffer) + } + } +}