Skip to content

Commit

Permalink
add chat and better logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Kenya-DK committed Feb 3, 2024
1 parent 7a5ddbc commit 977dbd1
Show file tree
Hide file tree
Showing 37 changed files with 778 additions and 712 deletions.
2 changes: 2 additions & 0 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ regex = "1.9.1"
directories = "5.0.1"
tokio = { version = "1", features = ["full"] }
csv = "1.1.6"
polars = { version = "0.30.0", features = ["lazy"] }
polars = { version = "0.30.0", features = ["lazy", "serde"] }
sqlx = { version = "0.7.1", features = ["runtime-tokio-native-tls", "sqlite"] }
once_cell = "1.7"
chrono = "0.4"
Expand Down
42 changes: 41 additions & 1 deletion src-tauri/src/commands/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ use crate::{
PACKAGEINFO,
};

use super::auth;

#[tauri::command]
pub async fn init(
settings: tauri::State<'_, Arc<Mutex<SettingsState>>>,
Expand Down Expand Up @@ -178,11 +180,14 @@ pub async fn update_settings(
let arced_mutex = Arc::clone(&settings_state);
let mut my_lock = arced_mutex.lock()?;

// Set Loggin Settings
my_lock.debug = settings.debug;

// Set Live Scraper Settings
my_lock.live_scraper = settings.live_scraper;

// Set Whisper Scraper Settings
my_lock.whisper_scraper = settings.whisper_scraper;
my_lock.notifications = settings.notifications;

my_lock.save_to_file().expect("Could not save settings");
Ok(())
Expand Down Expand Up @@ -213,6 +218,41 @@ pub fn show_notification(
);
}

#[tauri::command]
pub fn on_new_wfm_message(
message: crate::wfm_client::modules::chat::ChatMessage,
auth: tauri::State<'_, Arc<Mutex<AuthState>>>,
settings: tauri::State<'_, Arc<std::sync::Mutex<SettingsState>>>,
mh: tauri::State<'_, Arc<std::sync::Mutex<MonitorHandler>>>,
) {
let mh = mh.lock().unwrap();
let auth = auth.lock().unwrap().clone();
let settings = settings.lock().unwrap().clone().notifications.on_wfm_chat_message;

if auth.id == message.message_from {
return;
}

let content = settings.content.replace("<WFM_MESSAGE>", &message.raw_message.unwrap_or("".to_string()));
if settings.system_notify {
mh.show_notification(
&settings.title,
&content,
Some("https://i.imgur.com/UggEVVI.jpeg"),
Some("Default"),
);
}

if settings.discord_notify && settings.webhook.is_some() {
crate::helper::send_message_to_discord(
settings.webhook.unwrap_or("".to_string()),
settings.title,
content,
settings.user_ids,
);
}
}

#[tauri::command]
pub fn log(
component: String,
Expand Down
41 changes: 28 additions & 13 deletions src-tauri/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ pub struct ErrorApiResponse {
#[serde(rename = "error")]
pub error: String,

#[serde(rename = "message")]
pub message: Vec<String>,
#[serde(rename = "messages")]
pub messages: Vec<String>,

#[serde(skip_serializing_if = "Option::is_none", rename = "raw_response")]
pub raw_response: Option<String>,
Expand All @@ -37,22 +37,22 @@ pub enum ApiResult<T> {

#[derive(Debug)]
pub struct AppError {
component: &'static str,
component: String,
eyre_report: String,
log_level: LogLevel,
}
impl AppError {
// Custom constructor
pub fn new(component: &'static str, eyre_report: eyre::ErrReport) -> Self {
pub fn new(component: &str, eyre_report: eyre::ErrReport) -> Self {
AppError {
component,
component: component.to_string(),
eyre_report: format!("{:?}", eyre_report),
log_level: LogLevel::Critical,
}
}
// Custom constructor
pub fn new_api(
component: &'static str,
component: &str,
mut err: ErrorApiResponse,
eyre_report: eyre::ErrReport,
log_level: LogLevel,
Expand Down Expand Up @@ -80,23 +80,28 @@ impl AppError {
err.body = Some(payload.clone());
extra["ApiError"] = json!(err);
cause = format!(
"{}The request failed with status code {} to the url: {} with the following message: {}",
"{} The request failed with status code {} to the url: {} with the following message: {}",
cause,
err.status_code,
err.clone().url.unwrap_or("NONE".to_string()),
err.message.join(",")
err.messages.join(",")
);
new_err.eyre_report = format!(
"{}[J]{}[J]\n\nLocation:\n {}",
cause,
extra.to_string(),
backtrace
);
new_err.eyre_report = format!("{}[J]{}[J]\n\nLocation:\n {}", cause, extra, backtrace);
new_err
}
// Custom constructor
pub fn new_with_level(
component: &'static str,
component: &str,
eyre_report: eyre::ErrReport,
log_level: LogLevel,
) -> Self {
AppError {
component,
component: component.to_string(),
eyre_report: format!("{:?}", eyre_report),
log_level,
}
Expand All @@ -121,7 +126,11 @@ impl AppError {
}
}
Err(err) => {
json["error"] = json!(err.to_string());
json["ParsingError"] = json!({
"message": "Failed to parse the JSON in the error",
"error": err.to_string(),
"raw": json_str,
});
}
}
}
Expand Down Expand Up @@ -209,7 +218,13 @@ pub fn create_log_file(file: String, e: &AppError) {
crate::logger::dolog(
log_level,
component.as_str(),
format!("Location: {:?}, {:?}, Extra: <{:?}>", backtrace, cause, extra.to_string()).as_str(),
format!(
"Location: {:?}, {:?}, Extra: <{}>",
backtrace,
cause,
extra.to_string()
)
.as_str(),
true,
Some(file.as_str()),
);
Expand Down
102 changes: 48 additions & 54 deletions src-tauri/src/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ pub fn send_message_to_window(event: &str, data: Option<Value>) {
}
}


pub async fn get_app_info() -> Result<serde_json::Value, AppError> {
let packageinfo = PACKAGEINFO
.lock()
Expand Down Expand Up @@ -115,11 +114,12 @@ pub async fn get_app_info() -> Result<serde_json::Value, AppError> {
pub fn emit_progress(id: &str, i18n_key: &str, values: Option<Value>, is_completed: bool) {
send_message_to_window(
"Client:Update:Progress",
Some(json!({ "id": id, "i18n_key": i18n_key,"values": values, "isCompleted": is_completed})),
Some(
json!({ "id": id, "i18n_key": i18n_key,"values": values, "isCompleted": is_completed}),
),
);
}


pub fn emit_update(update_type: &str, operation: &str, data: Option<Value>) {
send_message_to_window(
"Client:Update",
Expand Down Expand Up @@ -370,41 +370,30 @@ pub fn get_column_values(
column: &str,
col_type: ColumnType,
) -> Result<ColumnValues, AppError> {
let error = format!(
"Column: {:?} ColumnType: {:?} Error: [] [J]{}[J]",
column,
col_type,
serde_json::to_value(&df).unwrap().to_string()
);

let df: DataFrame = match filter {
Some(filter) => df.lazy().filter(filter).collect().map_err(|e| {
AppError::new(
"Helper",
eyre!(format!(
"Column: {:?} ColumnType: {:?} Error: {:?}",
column, col_type, e
)),
)
AppError::new("Helper", eyre!(error.replace("[]", e.to_string().as_str())))
})?,
None => df,
};

let column_series = df.column(column).map_err(|e| {
AppError::new(
"Helper",
eyre!(format!(
"Column: {:?} ColumnType: {:?} Error: {:?}",
column, col_type, e
)),
)
})?;
let column_series = df
.column(column)
.map_err(|e| AppError::new("Helper", eyre!(error.replace("[]", e.to_string().as_str()))))?;

match col_type {
ColumnType::Bool => {
let values: Vec<bool> = column_series
.bool()
.map_err(|e| {
AppError::new(
"Helper",
eyre!(format!(
"Column: {:?} ColumnType: {:?} Error: {:?}",
column, col_type, e
)),
)
AppError::new("Helper", eyre!(error.replace("[]", e.to_string().as_str())))
})?
.into_iter()
.filter_map(|opt_val| opt_val)
Expand All @@ -416,13 +405,7 @@ pub fn get_column_values(
let values: Vec<f64> = column_series
.f64()
.map_err(|e| {
AppError::new(
"Helper",
eyre!(format!(
"Column: {:?} ColumnType: {:?} Error: {:?}",
column, col_type, e
)),
)
AppError::new("Helper", eyre!(error.replace("[]", e.to_string().as_str())))
})?
.into_iter()
.filter_map(|opt_val| opt_val)
Expand All @@ -434,13 +417,7 @@ pub fn get_column_values(
let values: Vec<i64> = column_series
.i64()
.map_err(|e| {
AppError::new(
"Helper",
eyre!(format!(
"Column: {:?} ColumnType: {:?} Error: {:?}",
column, col_type, e
)),
)
AppError::new("Helper", eyre!(error.replace("[]", e.to_string().as_str())))
})?
.into_iter()
.filter_map(|opt_val| opt_val)
Expand All @@ -451,13 +428,7 @@ pub fn get_column_values(
let values: Vec<i32> = column_series
.i32()
.map_err(|e| {
AppError::new(
"Helper",
eyre!(format!(
"Column: {:?} ColumnType: {:?} Error: {:?}",
column, col_type, e
)),
)
AppError::new("Helper", eyre!(error.replace("[]", e.to_string().as_str())))
})?
.into_iter()
.filter_map(|opt_val| opt_val)
Expand All @@ -468,13 +439,7 @@ pub fn get_column_values(
let values = column_series
.utf8()
.map_err(|e| {
AppError::new(
"Helper",
eyre!(format!(
"Column: {:?} ColumnType: {:?} Error: {:?}",
column, col_type, e
)),
)
AppError::new("Helper", eyre!(error.replace("[]", e.to_string().as_str())))
})?
.into_iter()
.filter_map(|opt_name| opt_name.map(String::from))
Expand Down Expand Up @@ -770,3 +735,32 @@ pub fn get_warframe_language() -> WarframeLanguage {
// Default to English in case of any error
WarframeLanguage::English
}

pub fn validate_json(json: &Value, required: &Value, path: &str) -> (Value, Vec<String>) {
let mut modified_json = json.clone();
let mut missing_properties = Vec::new();

if let Some(required_obj) = required.as_object() {
for (key, value) in required_obj {
let full_path = if path.is_empty() {
key.clone()
} else {
format!("{}.{}", path, key)
};

if !json.as_object().unwrap().contains_key(key) {
missing_properties.push(full_path.clone());
modified_json[key] = required_obj[key].clone();
} else if value.is_object() {
let sub_json = json.get(key).unwrap();
let (modified_sub_json, sub_missing) = validate_json(sub_json, value, &full_path);
if !sub_missing.is_empty() {
modified_json[key] = modified_sub_json;
missing_properties.extend(sub_missing);
}
}
}
}

(modified_json, missing_properties)
}
Loading

0 comments on commit 977dbd1

Please sign in to comment.