Skip to content

Commit

Permalink
Decorate with njump
Browse files Browse the repository at this point in the history
  • Loading branch information
dcadenas committed Apr 7, 2024
1 parent 472d114 commit 555caa3
Show file tree
Hide file tree
Showing 7 changed files with 216 additions and 80 deletions.
5 changes: 4 additions & 1 deletion src/actors/messages.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use crate::actors::utilities::OutputPortSubscriber;
use crate::domain_objects::*;
use nostr_sdk::prelude::Event;
use nostr_sdk::prelude::*;
use ractor::RpcReplyPort;
use std::fmt::Debug;

#[derive(Debug)]
pub enum SupervisorMessage {
Publish(ModeratedReport),
GetNip05(PublicKey, RpcReplyPort<Option<String>>),
}

#[derive(Debug)]
Expand All @@ -15,6 +17,7 @@ pub enum RelayEventDispatcherMessage {
SubscribeToEventReceived(OutputPortSubscriber<GiftWrappedReportRequest>),
EventReceived(Event),
Publish(ModeratedReport),
GetNip05(PublicKey, RpcReplyPort<Option<String>>),
}

#[derive(Debug)]
Expand Down
13 changes: 13 additions & 0 deletions src/actors/relay_event_dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ pub trait NostrPort: Send + Sync + Clone + 'static {
async fn connect(&self) -> Result<()>;
async fn reconnect(&self) -> Result<()>;
async fn publish(&self, event: Event) -> Result<()>;
async fn get_nip05(&self, public_key: PublicKey) -> Option<String>;

async fn subscribe(
&self,
Expand Down Expand Up @@ -161,6 +162,13 @@ impl<T: NostrPort> Actor for RelayEventDispatcher<T> {
moderated_report.event().id()
);
}
RelayEventDispatcherMessage::GetNip05(public_key, reply_port) => {
let maybe_nip05 = state.nostr_client.get_nip05(public_key).await;

if !reply_port.is_closed() {
reply_port.send(maybe_nip05)?;
}
}
}

Ok(())
Expand Down Expand Up @@ -239,6 +247,11 @@ mod tests {
async fn publish(&self, _event: Event) -> Result<()> {
Ok(())
}

async fn get_nip05(&self, _public_key: PublicKey) -> Option<String> {
None
}

async fn subscribe(
&self,
cancellation_token: CancellationToken,
Expand Down
25 changes: 20 additions & 5 deletions src/actors/supervisor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::actors::{
};
use anyhow::Result;
use nostr_sdk::prelude::*;
use ractor::{cast, Actor, ActorProcessingErr, ActorRef, SupervisionEvent};
use ractor::{call_t, cast, Actor, ActorProcessingErr, ActorRef, SupervisionEvent};
use tracing::error;

pub struct Supervisor<T, U> {
Expand Down Expand Up @@ -50,7 +50,7 @@ where
let (gift_unwrapper, _gift_unwrapper_handle) = Actor::spawn_linked(
Some("gift_unwrapper".to_string()),
GiftUnwrapper,
reportinator_keys.clone(),
reportinator_keys,
myself.get_cell(),
)
.await?;
Expand Down Expand Up @@ -83,11 +83,26 @@ where
&self,
_myself: ActorRef<Self::Msg>,
message: Self::Msg,
state: &mut Self::State,
event_dispatcher: &mut Self::State,
) -> Result<(), ActorProcessingErr> {
match message {
SupervisorMessage::Publish(report) => {
cast!(state, RelayEventDispatcherMessage::Publish(report))?;
Self::Msg::Publish(report) => {
cast!(
event_dispatcher,
RelayEventDispatcherMessage::Publish(report)
)?;
}
Self::Msg::GetNip05(request, reply_port) => {
let result = call_t!(
event_dispatcher,
RelayEventDispatcherMessage::GetNip05,
1000,
request
)?;

if !reply_port.is_closed() {
reply_port.send(result)?;
}
}
}
Ok(())
Expand Down
214 changes: 149 additions & 65 deletions src/adapters/http_server/slack_interactions_route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::domain_objects::{ModerationCategory, ReportRequest};
use anyhow::{anyhow, Context, Result};
use axum::{extract::State, routing::post, Extension, Router};
use nostr_sdk::prelude::*;
use ractor::cast;
use ractor::{call_t, cast, ActorRef};
use reqwest::Client as ReqwestClient;
use serde_json::{json, Value};
use slack_morphism::prelude::*;
Expand Down Expand Up @@ -60,72 +60,161 @@ async fn slack_interaction_handler(
let (response_url, slack_username, report_request, maybe_category) =
parse_slack_action(block_actions_event)?;

let message = if let Some(moderated_report) = report_request.report(maybe_category.clone())? {
let message = format!(
r#"
🚩 *New Moderation Report* 🚩
*Report Confirmed By:* {}
*Categorized As:* `{}`
*Report Id:* `{}`
*Requested By*: `{}`
*Reason:*
```
{}
```
*Reported Event Id:* `{}`
*Reported Event content:*
```
{}
```
"#,
slack_username,
maybe_category.unwrap(),
moderated_report.id(),
report_request.reporter_pubkey(),
report_request.reporter_text().unwrap_or(&"".to_string()),
report_request.reported_event().id,
report_request.reported_event().content
);
let message = slack_message(
message_dispatcher,
report_request,
maybe_category,
slack_username,
)
.await?;

send_slack_response(response_url.as_ref(), &message).await?;

Ok(())
}

async fn slack_message(
message_dispatcher: ActorRef<SupervisorMessage>,
report_request: ReportRequest,
maybe_category: Option<ModerationCategory>,
slack_username: String,
) -> Result<String, AppError> {
let reporter_nip05_markdown =
try_njump(message_dispatcher.clone(), report_request.reporter_pubkey()).await?;

let reported_nip05_markdown = try_njump(
message_dispatcher.clone(),
&report_request.reported_event().author(),
)
.await?;

if let Some(moderated_report) = report_request.report(maybe_category.as_ref())? {
let report_id = moderated_report.id();
cast!(
message_dispatcher,
SupervisorMessage::Publish(moderated_report)
)?;

message
} else {
format!(
r#"
⏭️ *Moderation Report Skipped* ⏭️
*Report Skipped By:* {}
*Requested By*: `{}`
*Reason:*
```
{}
```
*Reported Event Id:* `{}`
*Reported Event content:*
```
{}
```
"#,
let message = slack_processed_message(
slack_username,
report_request.reporter_pubkey(),
report_request.reporter_text().unwrap_or(&"".to_string()),
report_request.reported_event().id,
report_request.reported_event().content
)
};
maybe_category.unwrap(),
report_id,
reporter_nip05_markdown,
report_request,
reported_nip05_markdown,
);
return Ok(message);
}

send_slack_response(response_url.as_ref(), &message).await?;
Ok(slack_skipped_message(
slack_username,
reporter_nip05_markdown,
report_request,
reported_nip05_markdown,
))
}

Ok(())
fn slack_processed_message(
slack_username: String,
category: ModerationCategory,
report_id: EventId,
reporter_nip05_markdown: String,
report_request: ReportRequest,
reported_nip05_markdown: String,
) -> String {
let message = format!(
r#"
🚩 *New Moderation Report* 🚩
*Report Confirmed By:* {}
*Categorized As:* `{}`
*Report Id:* `{}`
*Requested By*: {}
*Reason:*
```
{}
```
*Reported Pubkey:* {}
*Reported Event Id:* `{}`
*Reported Event content:*
```
{}
```
"#,
slack_username,
category,
report_id,
reporter_nip05_markdown,
report_request.reporter_text().unwrap_or(&"".to_string()),
reported_nip05_markdown,
report_request.reported_event().id,
report_request.reported_event().content
);

let trimmed_string = message
.lines()
.map(|line| line.trim())
.collect::<Vec<&str>>()
.join("\n");

trimmed_string
}

fn slack_skipped_message(
slack_username: String,
reporter_nip05_markdown: String,
report_request: ReportRequest,
reported_nip05_markdown: String,
) -> String {
let message = format!(
r#"
⏭️ *Moderation Report Skipped* ⏭️
*Report Skipped By:* {}
*Requested By*: {}
*Reason:*
```
{}
```
*Reported Pubkey:* {}
*Reported Event Id:* `{}`
*Reported Event content:*
```
{}
```
"#,
slack_username,
reporter_nip05_markdown,
report_request.reporter_text().unwrap_or(&"".to_string()),
reported_nip05_markdown,
report_request.reported_event().id,
report_request.reported_event().content
);

let trimmed_string = message
.lines()
.map(|line| line.trim())
.collect::<Vec<&str>>()
.join("\n");

trimmed_string
}

async fn try_njump(
message_dispatcher: ActorRef<SupervisorMessage>,
pubkey: &PublicKey,
) -> Result<String> {
let maybe_reporter_nip05 =
call_t!(message_dispatcher, SupervisorMessage::GetNip05, 50, *pubkey)?;

Ok(maybe_reporter_nip05
.as_ref()
.map(|nip05| format!("https://njump.me/{}", nip05))
.unwrap_or(format!("`{}`", pubkey)))
}

fn parse_slack_action(
Expand Down Expand Up @@ -194,12 +283,7 @@ fn find_block_id(event_value: &Value, block_id_text: &str) -> Result<String, App
}

async fn send_slack_response(response_url: &str, response_text: &str) -> Result<()> {
let trimmed_string = response_text
.lines()
.map(|line| line.trim())
.collect::<Vec<&str>>()
.join("\n");
debug!("Sending response to slack: {:?}", trimmed_string);
debug!("Sending response to slack: {:?}", response_text);
let client = ReqwestClient::new();

let res = client
Expand All @@ -208,7 +292,7 @@ async fn send_slack_response(response_url: &str, response_text: &str) -> Result<
.body(
json!({
"replace_original": "true",
"text": trimmed_string,
"text": response_text,
})
.to_string(),
)
Expand Down
Loading

0 comments on commit 555caa3

Please sign in to comment.