charcoal_client/actions/
standard.rs

1//! Standard actions that can be called on a PlayerObject
2
3use std::time::Duration;
4use hearth_interconnect::errors::ErrorReport;
5use hearth_interconnect::messages::Metadata;
6use log::error;
7use crate::background::processor::IPCData;
8use crate::PlayerObject;
9use tokio::time::sleep;
10
11pub trait CharcoalEventHandler {
12    fn handle_error(&self, report: ErrorReport);
13    fn handle_metadata_response(&self, metadata: Metadata);
14}
15
16impl PlayerObject {
17    /// Register an error callback that will be called if an error occurs on this PlayerObject
18    pub async fn register_event_handler(
19        &mut self,
20        event_handler: impl CharcoalEventHandler + Send + 'static,
21    ) {
22        let mut t_rx = self.tx.subscribe();
23        let guild_id = self.guild_id.clone();
24        tokio::spawn(async move {
25            loop {
26                let x = t_rx.try_recv();
27                match x {
28                    Ok(d) => match d {
29                        IPCData::ErrorReport(error_report) => {
30                            if guild_id == error_report.guild_id {
31                                event_handler.handle_error(error_report);
32                            }
33                        }
34                        IPCData::MetadataResult(metadata) => {
35                            if guild_id == metadata.guild_id {
36                                event_handler.handle_metadata_response(metadata);
37                            }
38                        }
39                        _ => {}
40                    },
41                    Err(e) => {
42                        if e.to_string() != *"channel empty" {
43                            error!("Failed to RECV with error: {:?}", e);
44                        }
45                    }
46                }
47                sleep(Duration::from_millis(250)).await; // Don't max out the CPU
48            }
49        });
50    }
51}