Skip to content

Commit

Permalink
Merge branch 'main' into fix/bonus_tiers_ani
Browse files Browse the repository at this point in the history
  • Loading branch information
shanimal08 authored Jan 16, 2025
2 parents 20641dd + 785603b commit 6250a43
Show file tree
Hide file tree
Showing 19 changed files with 184 additions and 332 deletions.
6 changes: 0 additions & 6 deletions src-tauri/src/app_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,6 @@ pub(crate) struct AppConfig {
created_at: Option<DateTime<Utc>>,
mode: MiningMode,
display_mode: DisplayMode,
auto_mining: bool,
mine_on_app_start: bool,
p2pool_enabled: bool,
last_binaries_update_timestamp: SystemTime,
Expand Down Expand Up @@ -277,7 +276,6 @@ impl AppConfig {
created_at: None,
mode: MiningMode::Eco,
display_mode: DisplayMode::Light,
auto_mining: true,
mine_on_app_start: true,
p2pool_enabled: true,
last_binaries_update_timestamp: default_system_time(),
Expand Down Expand Up @@ -589,10 +587,6 @@ impl AppConfig {
Ok(())
}

pub fn auto_mining(&self) -> bool {
self.auto_mining
}

pub fn should_auto_launch(&self) -> bool {
self.should_auto_launch
}
Expand Down
60 changes: 3 additions & 57 deletions src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use crate::tor_adapter::TorConfig;
use crate::utils::shutdown_utils::stop_all_processes;
use crate::wallet_adapter::{TransactionInfo, WalletBalance};
use crate::wallet_manager::WalletManagerError;
use crate::{node_adapter, setup_inner, UniverseAppState, APPLICATION_FOLDER_ID};
use crate::{node_adapter, UniverseAppState, APPLICATION_FOLDER_ID};

use base64::prelude::*;
use keyring::Entry;
Expand All @@ -55,8 +55,6 @@ use std::thread::{available_parallelism, sleep};
use std::time::{Duration, Instant, SystemTime};
use tari_common::configuration::Network;
use tauri::{Manager, PhysicalPosition, PhysicalSize};
use tauri_plugin_sentry::sentry;
use tauri_plugin_sentry::sentry::protocol::Event;

const MAX_ACCEPTABLE_COMMAND_TIME: Duration = Duration::from_secs(1);
const LOG_TARGET: &str = "tari::universe::commands";
Expand Down Expand Up @@ -950,27 +948,6 @@ pub async fn send_feedback(
Ok(reference)
}

#[tauri::command]
pub async fn set_airdrop_access_token(
token: String,
_window: tauri::Window,
state: tauri::State<'_, UniverseAppState>,
_app: tauri::AppHandle,
) -> Result<(), String> {
let timer = Instant::now();
let mut write_lock = state.airdrop_access_token.write().await;
*write_lock = Some(token.clone());
if timer.elapsed() > MAX_ACCEPTABLE_COMMAND_TIME {
warn!(target: LOG_TARGET,
"set_airdrop_access_token took too long: {:?}",
timer.elapsed()
);
}
let mut in_memory_app_config = state.in_memory_config.write().await;
in_memory_app_config.airdrop_access_token = Some(token);
Ok(())
}

#[tauri::command]
pub async fn set_allow_telemetry(
allow_telemetry: bool,
Expand Down Expand Up @@ -1082,10 +1059,10 @@ pub async fn sign_ws_data(data: String) -> Result<SignWsDataResponse, String> {

let signature = key.sign(data.as_bytes());

return Ok(SignWsDataResponse {
Ok(SignWsDataResponse {
signature: BASE64_STANDARD.encode(signature.as_ref()),
pub_key,
});
})
}

#[tauri::command]
Expand Down Expand Up @@ -1417,37 +1394,6 @@ pub async fn set_visual_mode<'r>(
Ok(())
}

#[tauri::command]
pub async fn setup_application(
state: tauri::State<'_, UniverseAppState>,
app: tauri::AppHandle,
) -> Result<bool, String> {
let timer = Instant::now();
let rollback = state.setup_counter.write().await;
if rollback.get_value() {
warn!(target: LOG_TARGET, "setup_application has already been initialized, debouncing");
let res = state.config.read().await.auto_mining();
return Ok(res);
}
rollback.set_value(true, Duration::from_millis(1000)).await;
setup_inner(state.clone(), app).await.map_err(|e| {
warn!(target: LOG_TARGET, "Error setting up application: {:?}", e);
sentry::capture_event(Event {
level: sentry::Level::Error,
message: Some(e.to_string()),
culprit: Some("setup-inner".to_string()),
..Default::default()
});
e.to_string()
})?;

let res = state.config.read().await.auto_mining();
if timer.elapsed() > MAX_ACCEPTABLE_COMMAND_TIME {
warn!(target: LOG_TARGET, "setup_application took too long: {:?}", timer.elapsed());
}
Ok(res)
}

#[allow(clippy::too_many_lines)]
#[tauri::command]
pub async fn start_mining<'r>(
Expand Down
63 changes: 49 additions & 14 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ use crate::node_manager::NodeManager;
use crate::p2pool::models::P2poolStats;
use crate::p2pool_manager::{P2poolConfig, P2poolManager};
use crate::tor_manager::TorManager;
use crate::utils::auto_rollback::AutoRollback;
use crate::wallet_manager::WalletManager;
#[cfg(target_os = "macos")]
use utils::macos_utils::is_app_in_applications_folder;
Expand Down Expand Up @@ -160,15 +159,15 @@ async fn setup_inner(
app: tauri::AppHandle,
) -> Result<(), anyhow::Error> {
app.emit(
"message",
"setup_message",
SetupStatusEvent {
event_type: "setup_status".to_string(),
title: "starting-up".to_string(),
title_params: None,
progress: 0.0,
},
)
.inspect_err(|e| error!(target: LOG_TARGET, "Could not emit event 'message': {:?}", e))?;
.inspect_err(|e| error!(target: LOG_TARGET, "Could not emit event 'setup_message': {:?}", e))?;

#[cfg(target_os = "macos")]
if !cfg!(dev) && !is_app_in_applications_folder() {
Expand Down Expand Up @@ -224,6 +223,7 @@ async fn setup_inner(
let cpu_miner_config = state.cpu_miner_config.read().await;
let app_config = state.config.read().await;
let use_tor = app_config.use_tor();
let p2pool_enabled = app_config.p2pool_enabled();
drop(app_config);
let mm_proxy_manager = state.mm_proxy_manager.clone();

Expand Down Expand Up @@ -574,8 +574,17 @@ async fn setup_inner(
.await;
progress.set_max(75).await;
state.node_manager.wait_synced(progress.clone()).await?;
let mut telemetry_id = state
.telemetry_manager
.read()
.await
.get_unique_string()
.await;
if telemetry_id.is_empty() {
telemetry_id = "unknown_miner_tari_universe".to_string();
}

if state.config.read().await.p2pool_enabled() {
if p2pool_enabled {
let _unused = telemetry_service
.send(
"starting-p2pool".to_string(),
Expand Down Expand Up @@ -636,7 +645,7 @@ async fn setup_inner(
log_path: log_dir.clone(),
tari_address: cpu_miner_config.tari_address.clone(),
coinbase_extra: telemetry_id,
p2pool_enabled: config.p2pool_enabled(),
p2pool_enabled,
monero_nodes: config.mmproxy_monero_nodes().clone(),
use_monero_fail: config.mmproxy_use_monero_fail(),
})
Expand All @@ -655,15 +664,17 @@ async fn setup_inner(
drop(
app.clone()
.emit(
"message",
"setup_message",
SetupStatusEvent {
event_type: "setup_status".to_string(),
title: "application-started".to_string(),
title_params: None,
progress: 1.0,
},
)
.inspect_err(|e| error!(target: LOG_TARGET, "Could not emit event 'message': {:?}", e)),
.inspect_err(
|e| error!(target: LOG_TARGET, "Could not emit event 'setup_message': {:?}", e),
),
);

let move_handle = app.clone();
Expand Down Expand Up @@ -789,7 +800,6 @@ struct UniverseAppState {
updates_manager: UpdatesManager,
cached_p2pool_connections: Arc<RwLock<Option<Option<Connections>>>>,
cached_miner_metrics: Arc<RwLock<Option<MinerMetrics>>>,
setup_counter: Arc<RwLock<AutoRollback<bool>>>,
}

#[derive(Clone, serde::Serialize)]
Expand All @@ -798,6 +808,11 @@ struct Payload {
cwd: String,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
struct FEPayload {
token: String,
}

#[allow(clippy::too_many_lines)]
fn main() {
let _unused = fix_path_env::fix();
Expand Down Expand Up @@ -895,10 +910,10 @@ fn main() {
updates_manager,
cached_p2pool_connections: Arc::new(RwLock::new(None)),
cached_miner_metrics: Arc::new(RwLock::new(None)),
setup_counter: Arc::new(RwLock::new(AutoRollback::new(false))),
};

let app_state2 = app_state.clone();

let app = tauri::Builder::default()
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_sentry::init_with_no_injection(&client))
Expand Down Expand Up @@ -972,6 +987,24 @@ fn main() {
}
};

let token_state_clone = app.state::<UniverseAppState>().airdrop_access_token.clone();
let memory_state_clone = app.state::<UniverseAppState>().in_memory_config.clone();
app.listen("airdrop_token", move |event| {
let token_value = token_state_clone.clone();
let memory_value = memory_state_clone.clone();
tauri::async_runtime::spawn(async move {
info!(target: LOG_TARGET, "Getting token from Frontend");
let payload = event.payload();
let res = serde_json::from_str::<FEPayload>(payload).expect("No token");

let token = res.token;
let mut lock = token_value.write().await;
*lock = Some(token.clone());

let mut in_memory_app_config = memory_value.write().await;
in_memory_app_config.airdrop_access_token = Some(token);
});
});
// The start of needed restart operations. Break this out into a module if we need n+1
let tcp_tor_toggled_file = config_path.join("tcp_tor_toggled");
if tcp_tor_toggled_file.exists() {
Expand Down Expand Up @@ -1092,7 +1125,6 @@ fn main() {
commands::resolve_application_language,
commands::restart_application,
commands::send_feedback,
commands::set_airdrop_access_token,
commands::set_allow_telemetry,
commands::send_data_telemetry_service,
commands::set_application_language,
Expand All @@ -1112,7 +1144,6 @@ fn main() {
commands::set_tor_config,
commands::set_use_tor,
commands::set_visual_mode,
commands::setup_application,
commands::start_mining,
commands::stop_mining,
commands::update_applications,
Expand All @@ -1139,11 +1170,15 @@ fn main() {
);

app.run(move |app_handle, event| match event {
tauri::RunEvent::Ready { .. } => {
tauri::RunEvent::Ready => {
info!(target: LOG_TARGET, "App is ready");
let a = app_handle.clone();
let app_handle_clone = app_handle.clone();
tauri::async_runtime::spawn(async move {
let _unused = listen_to_frontend_ready(app_handle_clone).await;
tauri::async_runtime::spawn( async move {
let state = app_handle_clone.state::<UniverseAppState>().clone();
let _unused = listen_to_frontend_ready(app_handle_clone.clone()).await;
let _res = setup_inner(state, a.clone()).await
.inspect_err(|e| error!(target: LOG_TARGET, "Could not setup app: {:?}", e));
});
}
tauri::RunEvent::ExitRequested { api: _, .. } => {
Expand Down
6 changes: 4 additions & 2 deletions src-tauri/src/progress_tracker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,15 +123,17 @@ impl ProgressTrackerInner {
}
self.app_handle
.emit(
"message",
"setup_message",
SetupStatusEvent {
event_type: "setup_status".to_string(),
title,
title_params,
progress: progress_percentage,
},
)
.inspect_err(|e| error!(target: LOG_TARGET, "Could not emit event 'message': {:?}", e))
.inspect_err(
|e| error!(target: LOG_TARGET, "Could not emit event 'setup_message': {:?}", e),
)
.ok();
}
}
13 changes: 7 additions & 6 deletions src-tauri/src/telemetry_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,19 +280,19 @@ impl TelemetryManager {
pub async fn initialize(
&mut self,
airdrop_access_token: Arc<RwLock<Option<String>>>,
app: tauri::AppHandle,
app_handle: tauri::AppHandle,
) -> Result<()> {
info!(target: LOG_TARGET, "Starting telemetry manager");
self.airdrop_access_token = airdrop_access_token.clone();
self.start_telemetry_process(TelemetryFrequency::default().into(), app.clone())
self.start_telemetry_process(TelemetryFrequency::default().into(), app_handle)
.await?;
Ok(())
}

async fn start_telemetry_process(
&mut self,
timeout: Duration,
app: tauri::AppHandle,
app_handle: tauri::AppHandle,
) -> Result<(), TelemetryManagerError> {
let cpu_miner = self.cpu_miner.clone();
let gpu_status = self.gpu_status.clone();
Expand All @@ -314,7 +314,7 @@ impl TelemetryManager {
let airdrop_access_token_validated = validate_jwt(airdrop_access_token.clone()).await;
let telemetry_data = get_telemetry_data(&cpu_miner, &gpu_status, &node_status, &p2pool_status, &config, network).await;
let airdrop_api_url = in_memory_config_cloned.read().await.airdrop_api_url.clone();
handle_telemetry_data(telemetry_data, airdrop_api_url, airdrop_access_token_validated, app.clone()).await;
handle_telemetry_data(telemetry_data, airdrop_api_url, airdrop_access_token_validated, app_handle.clone()).await;
}
sleep(timeout);
}
Expand Down Expand Up @@ -577,7 +577,7 @@ async fn handle_telemetry_data(
telemetry: Result<TelemetryData, TelemetryManagerError>,
airdrop_api_url: String,
airdrop_access_token: Option<String>,
app: tauri::AppHandle,
app_handle: tauri::AppHandle,
) {
match telemetry {
Ok(telemetry) => {
Expand Down Expand Up @@ -610,7 +610,8 @@ async fn handle_telemetry_data(
referral_count: response_inner,
};

app.emit("UserPoints", emit_data)
app_handle
.emit("UserPoints", emit_data)
.map_err(|e| {
error!("could not send user points as an event: {}", e)
})
Expand Down
Loading

0 comments on commit 6250a43

Please sign in to comment.