Skip to content

Commit

Permalink
Merge branch 'refs/heads/main' into release
Browse files Browse the repository at this point in the history
  • Loading branch information
stringhandler committed Aug 6, 2024
2 parents 6eda659 + 577c484 commit e1a2aea
Show file tree
Hide file tree
Showing 24 changed files with 578 additions and 322 deletions.
2 changes: 0 additions & 2 deletions dist-isolation/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
window.__TAURI_ISOLATION_HOOK__ = (payload) => {
// let's not verify or modify anything, just print the content from the hook
console.log('hook', payload)
// TODO: Prevent command execution
// TODO: Perhaps whitelist commands
return payload
Expand Down
2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,4 @@ rand = "0.8.5"
custom-protocol = ["tauri/custom-protocol"]

[package.metadata.cargo-machete]
ignored = ["log4rs", "xz2"]
ignored = ["log4rs", "xz2", "libsqlite3-sys", "minotari_wallet_grpc_client"]
49 changes: 36 additions & 13 deletions src-tauri/src/binary_resolver.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::download_utils::{download_file, extract};
use crate::github;
use crate::{github, SetupStatusEvent};
use anyhow::{anyhow, Error};
use async_trait::async_trait;
use log::{error, info, warn};
Expand Down Expand Up @@ -104,19 +104,28 @@ impl LatestVersionApiAdapter for GithubReleasesAdapter {
&self,
version: &VersionDownloadInfo,
) -> Result<VersionAsset, Error> {
let mut name_suffix = "";
// TODO: add platform specific logic
#[cfg(target_os = "windows")]
let name_suffix = "windows-x64.exe.zip";
#[cfg(target_os = "macos")]
let name_suffix = "macos-arm64.zip";
#[cfg(target_os = "linux")]
let name_suffix = "linux-x86_64.zip";
if cfg!(target_os = "windows") {
name_suffix = "windows-x64.exe.zip";
}

if cfg!(target_os = "macos") && cfg!(target_arch = "aarch64") {
name_suffix = "macos-arm64.zip";
}

if cfg!(target_os = "macos") && cfg!(target_arch = "aarch64") {
name_suffix = "macos-arm64.zip";
}
if cfg!(target_os = "linux") {
name_suffix = "linux-x86_64.zip";
}

let platform = version
.assets
.iter()
.find(|a| a.name.ends_with(name_suffix))
.ok_or(anyhow::anyhow!("Failed to get windows_x64 asset"))?;
.ok_or(anyhow::anyhow!("Failed to get platform asset"))?;
Ok(platform.clone())
}
}
Expand Down Expand Up @@ -185,27 +194,41 @@ impl BinaryResolver {
}
}

pub async fn ensure_latest(&self, binary: Binaries) -> Result<Version, anyhow::Error> {
let version = self.ensure_latest_inner(binary, false).await?;
pub async fn ensure_latest(
&self,
binary: Binaries,
window: tauri::Window,
) -> Result<Version, anyhow::Error> {
let version = self.ensure_latest_inner(binary, false, window).await?;
Ok(version)
}

async fn ensure_latest_inner(
&self,
binary: Binaries,
force_download: bool,
window: tauri::Window,
) -> Result<Version, Error> {
let adapter = self
.adapters
.get(&binary)
.ok_or_else(|| anyhow!("No latest version adapter for this binary"))?;
let name = binary.name();
let _ = window.emit(
"message",
SetupStatusEvent {
event_type: "setup_status".to_string(),
title: format!("Fetching latest version of {}", name),
progress: 0.2,
},
);
let latest_release = adapter.fetch_latest_release().await?;
// TODO: validate that version doesn't have any ".." or "/" in it

let bin_folder = adapter
.get_binary_folder()
.join(&latest_release.version.to_string());
let lock = self.download_mutex.lock().await;
let _lock = self.download_mutex.lock().await;

if force_download {
println!("Cleaning up existing dir");
Expand Down Expand Up @@ -233,7 +256,7 @@ impl BinaryResolver {
info!(target: LOG_TARGET, "Downloading file from {}", &asset.url);
//
let in_progress_file = in_progress_dir.join(&asset.name);
download_file(&asset.url, &in_progress_file).await?;
download_file(&asset.url, &in_progress_file, window).await?;
info!(target: LOG_TARGET, "Renaming file");
info!(target: LOG_TARGET, "Extracting file");
let bin_dir = adapter
Expand All @@ -246,6 +269,7 @@ impl BinaryResolver {
Ok(latest_release.version)
}

#[allow(unreachable_statement)]
fn get_os_string() -> String {
#[cfg(target_os = "windows")]
{
Expand All @@ -267,7 +291,6 @@ impl BinaryResolver {
return "freebsd-x64".to_string();
}

#[allow(unreachable_patterns)]
panic!("Unsupported OS");
}
}
Expand Down
10 changes: 4 additions & 6 deletions src-tauri/src/cpu_miner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ impl CpuMiner {
cpu_miner_config: &CpuMinerConfig,
local_mm_proxy: &MmProxyManager,
base_path: PathBuf,
window: tauri::Window,
) -> Result<(), anyhow::Error> {
if self.watcher_task.is_some() {
warn!(target: LOG_TARGET, "Tried to start mining twice");
Expand All @@ -55,6 +56,7 @@ impl CpuMiner {
app_shutdown.clone(),
base_path,
cpu_miner_config.tari_address.clone(),
window.clone(),
)
.await?;
local_mm_proxy.wait_ready().await?;
Expand All @@ -67,7 +69,7 @@ impl CpuMiner {
}
};
let xmrig = XmrigAdapter::new(xmrig_node_connection, "44AFFq5kSiGBoZ4NMDwYtN18obc8AemS33DBLWs3H7otXft3XjrpDtQGv7SqSsaBYBb98uNbr2VBBEt7f2wfn3RVGQBEP3A".to_string() );
let (mut _rx, mut xmrig_child, client) = xmrig.spawn()?;
let (mut _rx, mut xmrig_child, client) = xmrig.spawn(window.clone())?;
self.api_client = Some(client);

self.watcher_task = Some(tauri::async_runtime::spawn(async move {
Expand Down Expand Up @@ -151,11 +153,7 @@ impl CpuMiner {
// Refresh CPUs again.
s.refresh_cpu_all();

let mut cpu_brand = "Unknown";
for cpu in s.cpus() {
cpu_brand = cpu.brand();
break;
}
let cpu_brand = s.cpus().get(0).map(|cpu| cpu.brand()).unwrap_or("Unknown");

let cpu_usage = s.global_cpu_usage() as u32;

Expand Down
24 changes: 23 additions & 1 deletion src-tauri/src/download_utils.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
pub async fn download_file(url: &str, destination: &Path) -> Result<(), anyhow::Error> {
pub async fn download_file(
url: &str,
destination: &Path,
window: tauri::Window,
) -> Result<(), anyhow::Error> {
println!("Downloading {} to {:?}", url, destination);
let response = reqwest::get(url).await?;

Expand All @@ -14,8 +18,25 @@ pub async fn download_file(url: &str, destination: &Path) -> Result<(), anyhow::
// Stream the response body directly to the file
let mut stream = response.bytes_stream();
while let Some(item) = stream.next().await {
let _ = window.emit(
"message",
SetupStatusEvent {
event_type: "setup_status".to_string(),
title: "Downloading".to_string(),
progress: 0.4,
},
);
dest.write_all(&item?).await?;
}

let _ = window.emit(
"message",
SetupStatusEvent {
event_type: "setup_status".to_string(),
title: "Downloaded".to_string(),
progress: 0.4,
},
);
println!("Done downloading");

Ok(())
Expand Down Expand Up @@ -51,6 +72,7 @@ pub async fn extract_gz(gz_path: &Path, dest_dir: &Path) -> std::io::Result<()>
Ok(())
}

use crate::SetupStatusEvent;
use anyhow::anyhow;
use async_zip::base::read::seek::ZipFileReader;
use flate2::read::GzDecoder;
Expand Down
69 changes: 56 additions & 13 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,49 +25,91 @@ use crate::mm_proxy_manager::MmProxyManager;
use crate::node_manager::NodeManager;
use crate::wallet_adapter::WalletBalance;
use crate::wallet_manager::WalletManager;
use dirs_next::data_dir;
use futures_util::{FutureExt, TryFutureExt};
use futures_util::TryFutureExt;
use log::{debug, error, info, warn};
use serde::Serialize;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::thread::sleep;
use std::{panic, process};
use tari_common_types::tari_address::TariAddress;
use tari_core::transactions::tari_amount::MicroMinotari;
use tari_shutdown::Shutdown;
use tauri::{api, RunEvent, UpdaterEvent};
use tauri::{RunEvent, UpdaterEvent};
use tokio::sync::RwLock;
use tokio::{join, try_join};
use tokio::try_join;

use crate::xmrig_adapter::XmrigAdapter;
use dirs_next::cache_dir;
use std::thread;
use std::time::Duration;

#[derive(Debug, Serialize, Deserialize, Clone)]
struct SetupStatusEvent {
event_type: String,
title: String,
progress: f64,
}

#[tauri::command]
async fn init<'r>(
async fn setup_application<'r>(
window: tauri::Window,
state: tauri::State<'r, UniverseAppState>,
app: tauri::AppHandle,
) -> Result<(), String> {
let _ = window.emit(
"message",
SetupStatusEvent {
event_type: "setup_status".to_string(),
title: "Starting up".to_string(),
progress: 0.0,
},
);
let data_dir = app.path_resolver().app_local_data_dir().unwrap();
let task1 = state
.node_manager
.ensure_started(state.shutdown.to_signal(), data_dir.clone())
.ensure_started(state.shutdown.to_signal(), data_dir.clone(), window.clone())
.map_err(|e| {
error!(target: LOG_TARGET, "Could not start node manager: {:?}", e);
e.to_string()
});

let task2 = state
.wallet_manager
.ensure_started(state.shutdown.to_signal(), data_dir)
.ensure_started(state.shutdown.to_signal(), data_dir, window.clone())
.map_err(|e| {
error!(target: LOG_TARGET, "Could not start wallet manager: {:?}", e);
e.to_string()
});

try_join!(task1, task2)?;
let task3 =
XmrigAdapter::ensure_latest(cache_dir().unwrap(), false, window.clone()).map_err(|e| {
error!(target: LOG_TARGET, "Could not download xmrig: {:?}", e);
e.to_string()
});

match try_join!(task1, task2, task3) {
Ok(_) => {
debug!(target: LOG_TARGET, "Applications started");
}
Err(e) => {
error!(target: LOG_TARGET, "Error starting applications: {:?}", e);
// return Err(e.to_string());
}
}
_ = window.emit(
"message",
SetupStatusEvent {
event_type: "setup_status".to_string(),
title: "Applications started".to_string(),
progress: 1.0,
},
);
Ok(())
}

#[tauri::command]
async fn start_mining<'r>(
_window: tauri::Window,
window: tauri::Window,
state: tauri::State<'r, UniverseAppState>,
app: tauri::AppHandle,
) -> Result<(), String> {
Expand All @@ -77,6 +119,7 @@ async fn start_mining<'r>(
.ensure_started(
state.shutdown.to_signal(),
app.path_resolver().app_local_data_dir().unwrap(),
window.clone(),
)
.await
.map_err(|e| e.to_string())?;
Expand All @@ -90,13 +133,13 @@ async fn start_mining<'r>(
&config,
&mm_proxy_manager,
app.path_resolver().app_local_data_dir().unwrap(),
window.clone(),
)
.await
.map_err(|e| {
dbg!(e.to_string());
e.to_string()
})?;
dbg!("command start finished");
Ok(())
}

Expand Down Expand Up @@ -151,7 +194,7 @@ async fn status(state: tauri::State<'_, UniverseAppState>) -> Result<AppStatus,
let wallet_balance = match state.wallet_manager.get_balance().await {
Ok(w) => w,
Err(e) => {
warn!(target: LOG_TARGET, "Error getting wallet balance: {:?}", e);
warn!(target: LOG_TARGET, "Error getting wallet balance: {}", e);
WalletBalance {
available_balance: MicroMinotari(0),
pending_incoming_balance: MicroMinotari(0),
Expand Down Expand Up @@ -293,7 +336,7 @@ fn main() {
}
})
.invoke_handler(tauri::generate_handler![
init,
setup_application,
status,
start_mining,
stop_mining
Expand Down
3 changes: 2 additions & 1 deletion src-tauri/src/merge_mining_adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ impl ProcessAdapter for MergeMiningProxyAdapter {
fn spawn_inner(
&self,
_log_folder: PathBuf,
window: tauri::Window,
) -> Result<(Self::Instance, Self::StatusMonitor), Error> {
let inner_shutdown = Shutdown::new();
let shutdown_signal = inner_shutdown.to_signal();
Expand Down Expand Up @@ -60,7 +61,7 @@ impl ProcessAdapter for MergeMiningProxyAdapter {
shutdown: inner_shutdown,
handle: Some(tokio::spawn(async move {
let version = BinaryResolver::current()
.ensure_latest(Binaries::MergeMiningProxy)
.ensure_latest(Binaries::MergeMiningProxy, window)
.await?;

let file_path = BinaryResolver::current()
Expand Down
Loading

0 comments on commit e1a2aea

Please sign in to comment.