Skip to content

Commit

Permalink
used sdk code to avoid code duplication - reduced user_rate.rs file (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
arkanoider authored Sep 22, 2023
1 parent fcef76f commit 1606446
Showing 1 changed file with 19 additions and 118 deletions.
137 changes: 19 additions & 118 deletions src/app/rate_user.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::util::{send_dm, update_user_rating_event};

use anyhow::Result;
use log::{error, info};
use log::error;
use mostro_core::order::Order;
use mostro_core::{Action, Content, Message, Rating, NOSTR_REPLACEABLE_EVENT_KIND};
use nostr_sdk::prelude::*;
Expand All @@ -10,135 +10,36 @@ use sqlx_crud::Crud;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use tokio::time::timeout;
use uuid::Uuid;

pub async fn send_relays_requests(client: &Client, filters: Filter) -> Option<Event> {
let relays = client.relays().await;

let relays_requests = relays.len();
let mut requests: Vec<tokio::task::JoinHandle<Option<Event>>> =
Vec::with_capacity(relays_requests);
let mut answers_requests = Vec::with_capacity(relays_requests);

for relay in relays.into_iter() {
info!("Requesting to relay : {}", relay.0.as_str());
// Spawn futures and join them at the end
requests.push(tokio::spawn(requests_relay(
client.clone(),
relay.clone(),
filters.clone(),
)));
}

// Get answers from relay
for req in requests {
let ev = req.await.unwrap();
if ev.is_some() {
answers_requests.push(ev.unwrap())
}
}
if answers_requests.is_empty() {
return None;
};

answers_requests.sort_by(|a, b| a.created_at.cmp(&b.created_at));
Some(answers_requests[0].clone())
}

pub async fn requests_relay(client: Client, relay: (Url, Relay), filters: Filter) -> Option<Event> {
let relrequest = get_nip_33_event(&relay.1, vec![filters.clone()], client);

// Buffer vector
let mut res: Option<Event> = None;

// Using a timeout of 3 seconds to avoid unresponsive relays to block the loop forever.
if let Ok(rx) = timeout(Duration::from_secs(3), relrequest).await {
match rx {
Some(m) => res = Some(m),
None => {
res = None;
info!("No requested events found on relay {}", relay.0.to_string());
}
}
}
res
}

pub async fn get_nip_33_event(
relay: &Relay,
filters: Vec<Filter>,
client: Client,
) -> Option<Event> {
// Subscribe
info!(
"Subscribing for all mostro orders to relay : {}",
relay.url().to_string()
);
let id = SubscriptionId::new(Uuid::new_v4().to_string());
let msg = ClientMessage::new_req(id.clone(), filters.clone());

info!("Message sent : {:?}", msg);

// Send msg to relay
relay
.send_msg(msg.clone(), Some(Duration::from_secs(30)))
.await
.unwrap();

// Wait notification from relays
let mut notifications = client.notifications();

let mut ev = None;
while let Ok(notification) = notifications.recv().await {
if let RelayPoolNotification::Message(_, msg) = notification {
match msg {
RelayMessage::Event {
subscription_id,
event,
} => {
if subscription_id == id {
ev = Some(event.as_ref().clone());
}
}
RelayMessage::EndOfStoredEvents(subscription_id) => {
if subscription_id == id {
break;
}
}
_ => (),
};
}
}

// Unsubscribe
relay
.send_msg(msg.clone(), Some(Duration::from_secs(30)))
.await
.unwrap();

ev
}

pub async fn get_counterpart_reputation(
user: &String,
my_keys: &Keys,
client: &Client,
) -> Option<Rating> {
) -> Result<Option<Rating>> {
// Request NIP33 of the counterparts

let filter = Filter::new()
let filters = Filter::new()
.author(my_keys.public_key().to_string())
.kind(Kind::Custom(NOSTR_REPLACEABLE_EVENT_KIND))
.identifier(user.to_string());
println!("Filter : {:?}", filter);
let event_nip33 = send_relays_requests(client, filter).await;

event_nip33.as_ref()?;
println!("Filter : {:?}", filters);

let mut user_reputation_event = client
.get_events_of(vec![filters], Some(Duration::from_secs(10)))
.await?;

// Check if vector of answers is empty
if user_reputation_event.is_empty() {
return Ok(None);
};

// Sore events by time
user_reputation_event.sort_by(|a, b| a.created_at.cmp(&b.created_at));

let reputation = Rating::from_json(&event_nip33.unwrap().content).unwrap();
let reputation = Rating::from_json(&user_reputation_event[0].content)?;

Some(reputation)
Ok(Some(reputation))
}

pub async fn update_user_reputation_action(
Expand Down Expand Up @@ -216,7 +117,7 @@ pub async fn update_user_reputation_action(
}

// Ask counterpart reputation
let rep = get_counterpart_reputation(&counterpart, my_keys, client).await;
let rep = get_counterpart_reputation(&counterpart, my_keys, client).await?;
// Here we have to update values of the review of the counterpart
let mut reputation;
// min_rate is 1 and max_rate is 5
Expand Down

0 comments on commit 1606446

Please sign in to comment.