Skip to content

Commit

Permalink
✨ feat(command): add update bar
Browse files Browse the repository at this point in the history
  • Loading branch information
CakeAL committed Nov 5, 2024
1 parent e0dd61d commit 8008904
Show file tree
Hide file tree
Showing 6 changed files with 190 additions and 73 deletions.
109 changes: 97 additions & 12 deletions src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use chrono::DateTime;
use tauri::{utils::config::WindowConfig, Manager};
use tauri::{ipc::Channel, utils::config::WindowConfig, Manager};

use crate::{
entities::{AppState, EveryLoginData},
entities::{AppState, DownloadEvent, EveryLoginData},
requests::*,
setting::Setting,
};
Expand Down Expand Up @@ -435,11 +435,7 @@ pub fn set_background_blur(
app_state: tauri::State<'_, AppState>,
blur: u32,
) -> Result<(), String> {
app_state
.setting
.write()
.unwrap()
.set_background_blur(blur);
app_state.setting.write().unwrap().set_background_blur(blur);
app_state
.setting
.read()
Expand All @@ -450,12 +446,25 @@ pub fn set_background_blur(
}

#[tauri::command(async)]
pub async fn manually_check_update(app: tauri::AppHandle) -> Result<(), String> {
#[cfg(not(any(target_os = "android", target_os = "linux")))]
crate::update(app, true)
.await
.map_err(|err| err.to_string())?;
pub async fn manually_check_update(
app: tauri::AppHandle,
manually: bool,
on_event: Channel<DownloadEvent>,
) -> Result<(), String> {
static mut AUTO_CHECK: bool = true; // 只能自动检查更新一次

#[cfg(not(any(target_os = "android", target_os = "linux")))]
if unsafe { AUTO_CHECK } || manually {
// 如果第一次自动或者手动更新
update(app, manually, on_event)
.await
.map_err(|err| err.to_string())?;
}
if !manually {
unsafe {
AUTO_CHECK = false;
}
}
if cfg!(target_os = "android") || cfg!(target_os = "linux") {
Err("安卓/Linux 不支持更新,请到 GitHub 查看是否有更新。".into())
} else {
Expand Down Expand Up @@ -518,3 +527,79 @@ pub async fn return_os_type() -> i32 {

res
}

#[cfg(not(any(target_os = "android", target_os = "linux")))]
async fn update(
app: tauri::AppHandle,
manually: bool,
on_event: Channel<DownloadEvent>,
) -> Result<(), String> {
use tauri_plugin_dialog::DialogExt;
#[cfg(not(any(target_os = "android", target_os = "linux")))]
use tauri_plugin_updater::UpdaterExt;

if let Some(update) = app
.updater()
.map_err(|e| e.to_string())?
.check()
.await
.map_err(|e| e.to_string())?
{
// 对话框
let answer = app
.dialog()
.message(format!(
"有新版本!{}->{}\n是否更新?",
update.current_version, update.version
))
.title("貌似有版本更新?")
.buttons(tauri_plugin_dialog::MessageDialogButtons::OkCancel)
.blocking_show();

if answer {
on_event
.send(DownloadEvent::Started { new_version: true })
.unwrap();

let mut downloaded = 0;
update
.download_and_install(
|chunk_length, content_length| {
downloaded += chunk_length;
// println!("downloaded {downloaded} from {content_length:?}");
on_event
.send(DownloadEvent::Progress {
downloaded,
content_length: content_length.unwrap_or_default(),
})
.unwrap();
},
|| {
// println!("download finished");
on_event
.send(DownloadEvent::Finished { finished: true })
.unwrap();
},
)
.await
.map_err(|e| e.to_string())?;
app.dialog()
.message("下载完成,点击重启")
.kind(tauri_plugin_dialog::MessageDialogKind::Info)
.title("这是个提示框")
.buttons(tauri_plugin_dialog::MessageDialogButtons::Ok)
.blocking_show();
// println!("update installed");
app.restart();
}
} else if manually {
app.dialog()
.message("没有更新😭")
.kind(tauri_plugin_dialog::MessageDialogKind::Info)
.title("这是个提示框")
.buttons(tauri_plugin_dialog::MessageDialogButtons::Ok)
.blocking_show();
}

Ok(())
}
16 changes: 15 additions & 1 deletion src-tauri/src/entities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,18 @@ pub struct AmmeterData {
pub message: String,
#[serde(rename = "statusCode")]
pub status_code: String,
}
}

#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase", tag = "event", content = "data")]
pub enum DownloadEvent {
#[serde(rename_all = "camelCase")]
Started { new_version: bool },
#[serde(rename_all = "camelCase")]
Progress {
downloaded: usize,
content_length: u64,
},
#[serde(rename_all = "camelCase")]
Finished { finished: bool },
}
56 changes: 1 addition & 55 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ use crate::commands::*;
use crate::entities::AppState;
use crate::setting::Setting;
use tauri::Manager;
use tauri_plugin_dialog::DialogExt;
#[cfg(not(any(target_os = "android", target_os = "linux")))]
use tauri_plugin_updater::UpdaterExt;


#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
Expand Down Expand Up @@ -60,10 +58,6 @@ pub fn run() {
#[cfg(not(any(target_os = "android", target_os = "linux")))]
{
background_init(app)?;
let handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
let _ = update(handle, false).await;
});
}
Ok(())
})
Expand Down Expand Up @@ -94,51 +88,3 @@ fn background_init(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error

Ok(())
}

#[cfg(not(any(target_os = "android", target_os = "linux")))]
async fn update(app: tauri::AppHandle, manually: bool) -> anyhow::Result<()> {
if let Some(update) = app.updater()?.check().await? {
// 对话框
let answer = app
.dialog()
.message(format!(
"有新版本!{}->{}\n是否更新?",
update.current_version, update.version
))
.title("貌似有版本更新?")
.buttons(tauri_plugin_dialog::MessageDialogButtons::OkCancel)
.blocking_show();

if answer {
let mut downloaded = 0;
update
.download_and_install(
|chunk_length, content_length| {
downloaded += chunk_length;
println!("downloaded {downloaded} from {content_length:?}");
},
|| {
println!("download finished");
},
)
.await?;
app.dialog()
.message("下载完成,点击重启")
.kind(tauri_plugin_dialog::MessageDialogKind::Info)
.title("这是个提示框")
.buttons(tauri_plugin_dialog::MessageDialogButtons::Ok)
.blocking_show();
println!("update installed");
app.restart();
}
} else if manually {
app.dialog()
.message("没有更新😭")
.kind(tauri_plugin_dialog::MessageDialogKind::Info)
.title("这是个提示框")
.buttons(tauri_plugin_dialog::MessageDialogButtons::Ok)
.blocking_show();
}

Ok(())
}
28 changes: 27 additions & 1 deletion src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { ref, computed, Ref, DefineComponent, onMounted } from "vue";
import { darkTheme } from "naive-ui";
import { invoke, convertFileSrc } from "@tauri-apps/api/core";
import { check_update, is_download, download_percent } from "./update";
// routers
import Login from "./pages/Login.vue";
Expand All @@ -14,6 +15,7 @@ import UnbindMacs from "./pages/UnbindMacs.vue";
import SpeedTest from "./pages/SpeedTest.vue";
import MonthlyUserLog from "./pages/MonthlyUserLog.vue";
import OtherTools from "./pages/OtherTools.vue";
type RouteComponent = DefineComponent<{}, {}, any>;
interface Routes {
Expand Down Expand Up @@ -109,6 +111,13 @@ const apply_background = async () => {
}
}
};
// download
onMounted(() => {
check_update(false);
});
</script>

<template>
Expand Down Expand Up @@ -136,6 +145,23 @@ const apply_background = async () => {
</n-loading-bar-provider>
</n-message-provider>
</n-modal-provider>
<n-progress
type="line"
:percentage="download_percent"
status="success"
indicator-placement="inside"
processing
class="download-progress"
v-if="is_download"
/>
</template>

<style scoped></style>
<style scoped>
.download-progress {
position: fixed;
bottom: 0;
left: 0;
width: calc(100vw - 20px);
padding: 10px;
}
</style>
9 changes: 5 additions & 4 deletions src/pages/Login.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useMessage, useLoadingBar } from "naive-ui";
import { ColorPaletteOutline } from "@vicons/ionicons5";
import { open } from "@tauri-apps/plugin-shell";
import { dataDir } from "@tauri-apps/api/path";
import { check_update } from "../update";
const loadingBar = useLoadingBar();
const pop_message = useMessage();
Expand Down Expand Up @@ -120,7 +121,7 @@ const railStyle = ({
};
const manually_check_update = async () => {
await invoke("manually_check_update").catch((err) => pop_message.error(err));
await check_update(true);
};
const submit_login_ustb_wifi = async () => {
Expand Down Expand Up @@ -153,9 +154,9 @@ const set_background_blur = async () => {
};
const open_config = async () => {
let path = await dataDir() + "/ustb-wifi-tools" ;
console.log(path);
// explorer 还是强的,能识别斜杠
let path = (await dataDir()) + "/ustb-wifi-tools";
// console.log(path);
await open(path);
};
</script>
Expand Down
45 changes: 45 additions & 0 deletions src/update.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { Channel, invoke } from "@tauri-apps/api/core";
import { ref } from "vue";

export const is_download = ref(false);
export const download_percent = ref(0);

type DownloadEvent =
| {
event: "started";
data: {
newVersion: boolean;
};
}
| {
event: "progress";
data: {
downloaded: number;
contentLength: number;
};
}
| {
event: "finished";
data: {
finished: boolean;
};
};

const onEvent = new Channel<DownloadEvent>();
onEvent.onmessage = (message) => {
if (message.event === "started") {
is_download.value = message.data.newVersion; // 这没有意义
} else if (message.event === "progress") {
download_percent.value =
parseFloat(
(message.data.downloaded / message.data.contentLength).toFixed(2)
) * 100;
}
};

export const check_update = async (manually: boolean) => {
await invoke("manually_check_update", {
manually,
onEvent,
}).catch((err) => console.log(err));
};

0 comments on commit 8008904

Please sign in to comment.