Frontend now listen to event sent from backend

This commit is contained in:
Quentin Legot 2023-04-25 20:08:07 +02:00
parent dce77e1e3d
commit 6697c38af0
5 changed files with 37 additions and 11 deletions

View File

@ -5,6 +5,7 @@ use std::path::{Path, self};
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use reqwest::{Client, StatusCode}; use reqwest::{Client, StatusCode};
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use tauri::Manager;
use tokio::{fs, io::{AsyncWriteExt, AsyncSeekExt}}; use tokio::{fs, io::{AsyncWriteExt, AsyncSeekExt}};
use crate::authentification::GameProfile; use crate::authentification::GameProfile;
@ -19,6 +20,13 @@ const ACTUAL_OS: OSName = OSName::Linux;
#[cfg(target_os="macos")] #[cfg(target_os="macos")]
const ACTUAL_OS: OSName = OSName::MacOsX; const ACTUAL_OS: OSName = OSName::MacOsX;
#[derive(Clone, serde::Serialize)]
struct ProgressMessage {
p_type: String,
current: usize,
total: usize,
}
pub struct ClientOptions<'a> { pub struct ClientOptions<'a> {
pub authorization: GameProfile, pub authorization: GameProfile,
pub root_path: &'a Path, pub root_path: &'a Path,
@ -55,7 +63,7 @@ impl<'a> MinecraftClient<'_> {
Ok(details) Ok(details)
} }
pub async fn download_assets(&mut self) -> Result<()> { pub async fn download_assets(&mut self, app: tauri::AppHandle) -> Result<()> {
// create root folder if it doesn't exist // create root folder if it doesn't exist
if !self.opts.root_path.exists() { if !self.opts.root_path.exists() {
fs::create_dir_all(self.opts.root_path).await?; fs::create_dir_all(self.opts.root_path).await?;
@ -65,7 +73,8 @@ impl<'a> MinecraftClient<'_> {
fs::create_dir(lib).await?; fs::create_dir(lib).await?;
} }
self.filter_non_necessary_librairies(); self.filter_non_necessary_librairies();
for (_, i) in self.details.libraries.iter().enumerate() { let total = self.details.libraries.len();
for (progress, i) in self.details.libraries.iter().enumerate() {
let p = i.downloads.artifact.path.clone(); let p = i.downloads.artifact.path.clone();
let mut splited = p.split("/").collect::<Vec<&str>>(); let mut splited = p.split("/").collect::<Vec<&str>>();
let filename = splited.pop().ok_or(anyhow::anyhow!("Invalid filename"))?; // remove last element let filename = splited.pop().ok_or(anyhow::anyhow!("Invalid filename"))?; // remove last element
@ -112,6 +121,7 @@ impl<'a> MinecraftClient<'_> {
} else { } else {
println!("{} already downloaded", i.name); println!("{} already downloaded", i.name);
} }
app.emit_all("progress", ProgressMessage { p_type: "libraries".to_string(), current: progress + 1, total })?;
} }
Ok(()) Ok(())

View File

@ -42,7 +42,7 @@ async fn login(app: tauri::AppHandle, _window: tauri::Window, state: tauri::Stat
} }
#[tauri::command] #[tauri::command]
async fn download(state: tauri::State<'_, Mutex<CustomState>>) -> Result<String, String> { async fn download(app: tauri::AppHandle, state: tauri::State<'_, Mutex<CustomState>>) -> Result<String, String> {
if let Some(base_dir) = BaseDirs::new() { if let Some(base_dir) = BaseDirs::new() {
let data_folder = base_dir.data_dir().join(".altarik_test"); let data_folder = base_dir.data_dir().join(".altarik_test");
let root_path = data_folder.as_path(); let root_path = data_folder.as_path();
@ -66,7 +66,7 @@ async fn download(state: tauri::State<'_, Mutex<CustomState>>) -> Result<String,
let client = MinecraftClient::new(&opts).await; let client = MinecraftClient::new(&opts).await;
match client { match client {
Ok(mut client) => { Ok(mut client) => {
match client.download_assets().await { match client.download_assets(app).await {
Ok(_) => { Ok(_) => {
Ok("Content downloaded".to_string()) Ok("Content downloaded".to_string())
}, },

View File

@ -1,4 +1,4 @@
export default { const vue = {
data() { data() {
return { return {
button_message: "Login to minecraft", button_message: "Login to minecraft",
@ -7,6 +7,15 @@ export default {
hideDownloadButton: true, hideDownloadButton: true,
} }
}, },
created() {
console.log(this)
this.listen('progress', (event) => {
// event.event is the event name (useful if you want to use a single callback fn for multiple event types)
// event.payload is the payload object
console.log(event.payload)
this.greet_message = event.payload
})
},
methods: { methods: {
login (e) { login (e) {
e.preventDefault() e.preventDefault()
@ -25,7 +34,7 @@ export default {
e.preventDefault() e.preventDefault()
if(!this.hideDownloadButton) { if(!this.hideDownloadButton) {
this.invoke("download", {}).then(value => { this.invoke("download", {}).then(value => {
this.greet_message = value // this.greet_message = value
}).catch(err => { }).catch(err => {
this.greet_message = "Error: " + err this.greet_message = "Error: " + err
}) })
@ -33,7 +42,8 @@ export default {
}, },
}, },
props: { props: {
invoke: Object invoke: Object,
listen: Object,
}, },
template: ` template: `
<h1>Welcome to Tauri!</h1> <h1>Welcome to Tauri!</h1>
@ -48,3 +58,5 @@ export default {
<p id="greet-msg">{{ greet_message }}</p> <p id="greet-msg">{{ greet_message }}</p>
` `
} }
export default vue;

View File

@ -16,7 +16,7 @@
<body> <body>
<div id="container"> <div id="container">
<loginpage :invoke="invoke"></loginpage> <loginpage :invoke="invoke" :listen="listen"></loginpage>
</div> </div>
</body> </body>
</html> </html>

View File

@ -1,13 +1,15 @@
const { invoke } = window.__TAURI__.tauri; const { invoke } = window.__TAURI__.tauri;
const { listen } = window.__TAURI__.event;
const { createApp } = Vue const { createApp } = Vue
import loginpage from './components/login.js' import loginpage from './components/login.js'
createApp({ let app = createApp({
data() { data() {
return { return {
invoke: invoke invoke: invoke,
listen: listen,
} }
}, },
mounted() { mounted() {
@ -16,4 +18,6 @@ createApp({
components: { components: {
loginpage loginpage
} }
}).mount('#container') });
app.mount('#container')