Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/h0lly w00dz z updater #5632

Merged
merged 7 commits into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions app/components/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ import Locale, {
changeLang,
getLang,
} from "../locales";
import { copyToClipboard } from "../utils";
import { copyToClipboard, clientUpdate, semverCompare } from "../utils";
import Link from "next/link";
import {
Anthropic,
Expand Down Expand Up @@ -585,7 +585,7 @@ export function Settings() {
const [checkingUpdate, setCheckingUpdate] = useState(false);
const currentVersion = updateStore.formatVersion(updateStore.version);
const remoteId = updateStore.formatVersion(updateStore.remoteVersion);
const hasNewVersion = currentVersion !== remoteId;
const hasNewVersion = semverCompare(currentVersion, remoteId) === -1;
const updateUrl = getClientConfig()?.isApp ? RELEASE_URL : UPDATE_URL;

function checkUpdate(force = false) {
Expand Down Expand Up @@ -1357,9 +1357,17 @@ export function Settings() {
{checkingUpdate ? (
<LoadingIcon />
) : hasNewVersion ? (
<Link href={updateUrl} target="_blank" className="link">
{Locale.Settings.Update.GoToUpdate}
</Link>
clientConfig?.isApp ? (
<IconButton
icon={<ResetIcon></ResetIcon>}
text={Locale.Settings.Update.GoToUpdate}
onClick={() => clientUpdate()}
/>
) : (
<Link href={updateUrl} target="_blank" className="link">
{Locale.Settings.Update.GoToUpdate}
</Link>
)
lloydzhou marked this conversation as resolved.
Show resolved Hide resolved
) : (
<IconButton
icon={<ResetIcon></ResetIcon>}
Expand Down
7 changes: 7 additions & 0 deletions app/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ declare interface Window {
isPermissionGranted(): Promise<boolean>;
sendNotification(options: string | Options): void;
};
updater: {
checkUpdate(): Promise<UpdateResult>;
installUpdate(): Promise<void>;
onUpdaterEvent(
handler: (status: UpdateStatusResult) => void,
): Promise<UnlistenFn>;
};
http: {
fetch<T>(
url: string,
Expand Down
2 changes: 2 additions & 0 deletions app/locales/cn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,8 @@ const cn = {
IsChecking: "正在检查更新...",
FoundUpdate: (x: string) => `发现新版本:${x}`,
GoToUpdate: "前往更新",
Success: "Update Succesfull.",
Failed: "Update Failed.",
lloydzhou marked this conversation as resolved.
Show resolved Hide resolved
},
SendKey: "发送键",
Theme: "主题",
Expand Down
2 changes: 2 additions & 0 deletions app/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,8 @@ const en: LocaleType = {
IsChecking: "Checking update...",
FoundUpdate: (x: string) => `Found new version: ${x}`,
GoToUpdate: "Update",
Success: "Update Successful.",
Failed: "Update Failed.",
},
SendKey: "Send Key",
Theme: "Theme",
Expand Down
2 changes: 2 additions & 0 deletions app/store/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from "../constant";
import { getClientConfig } from "../config/client";
import { createPersistStore } from "../utils/store";
import { clientUpdate } from "../utils";
import ChatGptIcon from "../icons/chatgpt.png";
import Locale from "../locales";
import { ClientApi } from "../client/api";
Expand Down Expand Up @@ -119,6 +120,7 @@ export const useUpdateStore = createPersistStore(
icon: `${ChatGptIcon.src}`,
sound: "Default",
});
clientUpdate();
}
}
});
Expand Down
34 changes: 34 additions & 0 deletions app/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -386,3 +386,37 @@ export function getOperationId(operation: {
`${operation.method.toUpperCase()}${operation.path.replaceAll("/", "_")}`
);
}

export function clientUpdate() {
// this a wild for updating client app
return window.__TAURI__?.updater
.checkUpdate()
.then((updateResult) => {
if (updateResult.shouldUpdate) {
window.__TAURI__?.updater
.installUpdate()
.then((result) => {
showToast(Locale.Settings.Update.Success);
})
.catch((e) => {
console.error("[Install Update Error]", e);
showToast(Locale.Settings.Update.Failed);
});
}
})
.catch((e) => {
console.error("[Check Update Error]", e);
showToast(Locale.Settings.Update.Failed);
});
}
Comment on lines +390 to +411
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

Improve error handling, user experience, and return value in the clientUpdate function.

While the function implements the basic update flow, there are several areas for improvement:

  1. Error Handling: Check if window.__TAURI__ is defined before accessing it to prevent runtime errors in non-Tauri environments.
  2. User Confirmation: Add user confirmation before installing updates for better user experience.
  3. Return Value: Consider returning a boolean indicating whether an update was installed.
  4. Async/Await: Use async/await for better readability and error handling.

Consider refactoring the function as follows:

export async function clientUpdate(): Promise<boolean> {
  if (!window.__TAURI__?.updater) {
    console.error("Tauri updater not available");
    return false;
  }

  try {
    const updateResult = await window.__TAURI__.updater.checkUpdate();
    if (updateResult.shouldUpdate) {
      const userConfirmed = await showConfirmDialog(Locale.Settings.Update.Confirm);
      if (userConfirmed) {
        await window.__TAURI__.updater.installUpdate();
        showToast(Locale.Settings.Update.Success);
        return true;
      }
    } else {
      showToast(Locale.Settings.Update.NoUpdate);
    }
  } catch (e) {
    console.error("[Update Error]", e);
    showToast(Locale.Settings.Update.Failed);
  }
  return false;
}

This refactored version addresses the issues mentioned above and improves overall robustness and user experience.

Note: You'll need to implement the showConfirmDialog function and add the necessary locale strings.


// https://gist.github.com/iwill/a83038623ba4fef6abb9efca87ae9ccb
export function semverCompare(a: string, b: string) {
if (a.startsWith(b + "-")) return -1;
if (b.startsWith(a + "-")) return 1;
return a.localeCompare(b, undefined, {
numeric: true,
sensitivity: "case",
caseFirst: "upper",
});
}
lloydzhou marked this conversation as resolved.
Show resolved Hide resolved
Loading