Skip to content

Commit

Permalink
Access event dispatcher from http handler
Browse files Browse the repository at this point in the history
  • Loading branch information
dcadenas committed Mar 29, 2024
1 parent 9425640 commit 7a3e762
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 15 deletions.
19 changes: 15 additions & 4 deletions src/adapters/http_server.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
mod app_errors;
mod slack_interactions_route;
use crate::actors::messages::RelayEventDispatcherMessage;
use anyhow::{Context, Result};
use axum::{extract::State, http::HeaderMap, response::Html};
use axum::{response::IntoResponse, routing::get, Router};
use handlebars::Handlebars;
use ractor::ActorRef;
use serde_json::json;
use slack_interactions_route::slack_interactions_route;
use std::env;
Expand All @@ -22,27 +24,36 @@ use tracing::Level;
#[derive(Clone)]
pub struct WebAppState {
hb: Arc<Handlebars<'static>>,
event_dispatcher: ActorRef<RelayEventDispatcherMessage>,
}

pub struct HttpServer;

impl HttpServer {
pub async fn run(cancellation_token: CancellationToken) -> Result<()> {
let web_app_state = create_web_app_state()?;
pub async fn run(
cancellation_token: CancellationToken,
event_dispatcher: ActorRef<RelayEventDispatcherMessage>,
) -> Result<()> {
let web_app_state = create_web_app_state(event_dispatcher)?;
let router = create_router(&web_app_state)?;

start_http_server(router, cancellation_token).await
}
}

fn create_web_app_state() -> Result<WebAppState> {
fn create_web_app_state(
event_dispatcher: ActorRef<RelayEventDispatcherMessage>,
) -> Result<WebAppState> {
let templates_dir = env::var("TEMPLATES_DIR").unwrap_or_else(|_| "/app/templates".to_string());
let mut hb = Handlebars::new();

hb.register_template_file("root", format!("{}/root.hbs", templates_dir))
.map_err(|e| anyhow::anyhow!("Failed to load template: {}", e))?;

Ok(WebAppState { hb: Arc::new(hb) })
Ok(WebAppState {
hb: Arc::new(hb),
event_dispatcher,
})
}

fn create_router<SlackLayer>(web_app_state: &WebAppState) -> Result<Router>
Expand Down
38 changes: 28 additions & 10 deletions src/adapters/http_server/slack_interactions_route.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use super::app_errors::AppError;
use super::WebAppState;
use anyhow::{Context, Result};
use axum::Extension;
use axum::{routing::post, Router};
use nostr_sdk::Event;
use anyhow::{anyhow, Context, Result};
use axum::{extract::State, routing::post, Extension, Router};
use nostr_sdk::prelude::*;
use reqwest::Client;
use serde_json::{json, Value};
use slack_morphism::prelude::*;
Expand Down Expand Up @@ -44,6 +43,7 @@ fn prepare_listener_environment(
}

async fn slack_interaction_handler(
State(state): State<WebAppState>,
Extension(event): Extension<SlackInteractionEvent>,
) -> Result<(), AppError> {
match event {
Expand Down Expand Up @@ -99,25 +99,43 @@ async fn slack_interaction_handler(
return Err(AppError::action_error());
};

let event_value = rich_text["elements"][0]["elements"][0]["text"].to_owned();
///let event = Event::from_value()?;
// TODO: Ugly way to get the event id. Need to find a better way to do this.
let Some(event_value) = rich_text["elements"][0]["elements"][0]["text"].as_str() else {
return Err(AppError::action_error());
};

let event = Event::from_json(event_value).map_err(|e| {
anyhow!(
"Failed to parse event from value: {:?}. Error: {:?}",
event_value,
e
)
})?;

info!("Reported Event Block: {:?}", event_value);
info!("Reported Event Block: {:?}", event);
info!(
"Received interaction from {}. Action: {}, Value: {}",
username, action_id, value
);
respond_with_replace(&response_url.to_string(), username, text).await?;
respond_with_replace(&response_url.to_string(), username, text, event.id).await?;
}
_ => {}
}

Ok(())
}

async fn respond_with_replace(response_url: &str, username: &str, text: &str) -> Result<()> {
async fn respond_with_replace(
response_url: &str,
username: &str,
text: &str,
event_id: EventId,
) -> Result<()> {
let client = Client::new();
let response_text = format!("{} selected: {}", username, text);
let response_text = format!(
"`{}` selected `{}` for event id `{}`",
username, text, event_id
);

let res = client
.post(response_url)
Expand Down
3 changes: 2 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ async fn start_server(
// Connect as the last message once everything is wired up
cast!(event_dispatcher, RelayEventDispatcherMessage::Connect)?;

manager.spawn_service(HttpServer::run);
manager
.spawn_service(|cancellation_token| HttpServer::run(cancellation_token, event_dispatcher));

manager
.listen_stop_signals()
Expand Down

0 comments on commit 7a3e762

Please sign in to comment.