mirror of https://github.com/jetkvm/kvm.git
refactor: ota redirecting (#898)
* refactor: improve URL handling in RebootingOverlay component * refactor: enhance redirect URL handling in TryUpdate function * refactor: disable old ota rebooting method in new version * refactor: streamline version retrieval logic and enhance error handling in useVersion hook * refactor: rename to RedirectTo * fix: force page reload when redirecting from reboot actions * refactor: consolidate sleep utility and update usages across components * refactor: update JsonRpcCallOptions to use maxAttempts and attemptTimeoutMs, implement exponential backoff for retries --------- Co-authored-by: Adam Shiervani <adamshiervani@fastmail.com>
This commit is contained in:
parent
9a4d061034
commit
ce9f95b8c8
|
|
@ -29,7 +29,7 @@ func (s *RpcNetworkSettings) ToNetworkConfig() *types.NetworkConfig {
|
|||
|
||||
type PostRebootAction struct {
|
||||
HealthCheck string `json:"healthCheck"`
|
||||
RedirectUrl string `json:"redirectUrl"`
|
||||
RedirectTo string `json:"redirectTo"`
|
||||
}
|
||||
|
||||
func toRpcNetworkSettings(config *types.NetworkConfig) *RpcNetworkSettings {
|
||||
|
|
@ -202,7 +202,7 @@ func shouldRebootForNetworkChange(oldConfig, newConfig *types.NetworkConfig) (re
|
|||
if newIPv4Mode == "static" && oldIPv4Mode != "static" {
|
||||
postRebootAction = &PostRebootAction{
|
||||
HealthCheck: fmt.Sprintf("//%s/device/status", newConfig.IPv4Static.Address.String),
|
||||
RedirectUrl: fmt.Sprintf("//%s", newConfig.IPv4Static.Address.String),
|
||||
RedirectTo: fmt.Sprintf("//%s", newConfig.IPv4Static.Address.String),
|
||||
}
|
||||
l.Info().Interface("postRebootAction", postRebootAction).Msg("IPv4 mode changed to static, reboot required")
|
||||
}
|
||||
|
|
@ -219,7 +219,7 @@ func shouldRebootForNetworkChange(oldConfig, newConfig *types.NetworkConfig) (re
|
|||
newConfig.IPv4Static.Address.String != oldConfig.IPv4Static.Address.String {
|
||||
postRebootAction = &PostRebootAction{
|
||||
HealthCheck: fmt.Sprintf("//%s/device/status", newConfig.IPv4Static.Address.String),
|
||||
RedirectUrl: fmt.Sprintf("//%s", newConfig.IPv4Static.Address.String),
|
||||
RedirectTo: fmt.Sprintf("//%s", newConfig.IPv4Static.Address.String),
|
||||
}
|
||||
|
||||
l.Info().Interface("postRebootAction", postRebootAction).Msg("IPv4 static config changed, reboot required")
|
||||
|
|
|
|||
15
ota.go
15
ota.go
|
|
@ -489,9 +489,22 @@ func TryUpdate(ctx context.Context, deviceId string, includePreRelease bool) err
|
|||
if rebootNeeded {
|
||||
scopedLogger.Info().Msg("System Rebooting due to OTA update")
|
||||
|
||||
// Build redirect URL with conditional query parameters
|
||||
redirectTo := "/settings/general/update"
|
||||
queryParams := url.Values{}
|
||||
if systemUpdateAvailable {
|
||||
queryParams.Set("systemVersion", remote.SystemVersion)
|
||||
}
|
||||
if appUpdateAvailable {
|
||||
queryParams.Set("appVersion", remote.AppVersion)
|
||||
}
|
||||
if len(queryParams) > 0 {
|
||||
redirectTo += "?" + queryParams.Encode()
|
||||
}
|
||||
|
||||
postRebootAction := &PostRebootAction{
|
||||
HealthCheck: "/device/status",
|
||||
RedirectUrl: "/settings/general/update?version=" + remote.SystemVersion,
|
||||
RedirectTo: redirectTo,
|
||||
}
|
||||
|
||||
if err := hwReboot(true, postRebootAction, 10*time.Second); err != nil {
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import { SelectMenuBasic } from "@components/SelectMenuBasic";
|
|||
import { SettingsSectionHeader } from "@components/SettingsSectionHeader";
|
||||
import Fieldset from "@components/Fieldset";
|
||||
import notifications from "@/notifications";
|
||||
import { sleep } from "@/utils";
|
||||
|
||||
export interface USBConfig {
|
||||
vendor_id: string;
|
||||
|
|
@ -108,7 +109,7 @@ export function UsbDeviceSetting() {
|
|||
}
|
||||
|
||||
// We need some time to ensure the USB devices are updated
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
await sleep(2000);
|
||||
setLoading(false);
|
||||
syncUsbDeviceConfig();
|
||||
notifications.success(m.usb_device_updated());
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import { SelectMenuBasic } from "@components/SelectMenuBasic";
|
|||
import { SettingsItem } from "@components/SettingsItem";
|
||||
import notifications from "@/notifications";
|
||||
import { m } from "@localizations/messages.js";
|
||||
import { sleep } from "@/utils";
|
||||
|
||||
const generatedSerialNumber = [generateNumber(1, 9), generateHex(7, 7), 0, 1].join("&");
|
||||
|
||||
|
|
@ -123,7 +124,7 @@ export function UsbInfoSetting() {
|
|||
}
|
||||
|
||||
// We need some time to ensure the USB devices are updated
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
await sleep(2000);
|
||||
setLoading(false);
|
||||
notifications.success(
|
||||
m.usb_config_set_success({ manufacturer: usbConfig.manufacturer, product: usbConfig.product }),
|
||||
|
|
|
|||
|
|
@ -474,8 +474,15 @@ export function RebootingOverlay({ show, postRebootAction }: RebootingOverlayPro
|
|||
|
||||
if (response.ok) {
|
||||
// Device is available, redirect to the specified URL
|
||||
console.log('Device is available, redirecting to:', postRebootAction.redirectUrl);
|
||||
window.location.href = postRebootAction.redirectUrl;
|
||||
console.log('Device is available, redirecting to:', postRebootAction.redirectTo);
|
||||
|
||||
// URL constructor handles all cases elegantly:
|
||||
// - Absolute paths: resolved against current origin
|
||||
// - Protocol-relative URLs: resolved with current protocol
|
||||
// - Fully qualified URLs: used as-is
|
||||
const targetUrl = new URL(postRebootAction.redirectTo, window.location.origin);
|
||||
|
||||
window.location.href = targetUrl.href;
|
||||
window.location.reload();
|
||||
}
|
||||
} catch (err) {
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ interface JsonRpcResponse {
|
|||
|
||||
export type PostRebootAction = {
|
||||
healthCheck: string;
|
||||
redirectUrl: string;
|
||||
redirectTo: string;
|
||||
} | null;
|
||||
|
||||
// Utility function to append stats to a Map
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import {
|
|||
import { useHidRpc } from "@/hooks/useHidRpc";
|
||||
import { JsonRpcResponse, useJsonRpc } from "@/hooks/useJsonRpc";
|
||||
import { hidKeyToModifierMask, keys, modifiers } from "@/keyboardMappings";
|
||||
import { sleep } from "@/utils";
|
||||
|
||||
const MACRO_RESET_KEYBOARD_STATE = {
|
||||
keys: new Array(hidKeyBufferSize).fill(0),
|
||||
|
|
@ -31,8 +32,6 @@ export interface MacroStep {
|
|||
|
||||
export type MacroSteps = MacroStep[];
|
||||
|
||||
const sleep = (ms: number): Promise<void> => new Promise(resolve => setTimeout(resolve, ms));
|
||||
|
||||
export default function useKeyboard() {
|
||||
const { send } = useJsonRpc();
|
||||
const { rpcDataChannel } = useRTCStore();
|
||||
|
|
@ -97,7 +96,8 @@ export default function useKeyboard() {
|
|||
[send, setKeysDownState],
|
||||
);
|
||||
|
||||
const sendKeystrokeLegacy = useCallback(async (keys: number[], modifier: number, ac?: AbortController) => {
|
||||
const sendKeystrokeLegacy = useCallback(
|
||||
async (keys: number[], modifier: number, ac?: AbortController) => {
|
||||
return await new Promise<void>((resolve, reject) => {
|
||||
const abortListener = () => {
|
||||
reject(new Error("Keyboard report aborted"));
|
||||
|
|
@ -105,16 +105,14 @@ export default function useKeyboard() {
|
|||
|
||||
ac?.signal?.addEventListener("abort", abortListener);
|
||||
|
||||
send(
|
||||
"keyboardReport",
|
||||
{ keys, modifier },
|
||||
params => {
|
||||
send("keyboardReport", { keys, modifier }, params => {
|
||||
if ("error" in params) return reject(params.error);
|
||||
resolve();
|
||||
},
|
||||
);
|
||||
});
|
||||
}, [send]);
|
||||
});
|
||||
},
|
||||
[send],
|
||||
);
|
||||
|
||||
const KEEPALIVE_INTERVAL = 50;
|
||||
|
||||
|
|
@ -149,7 +147,6 @@ export default function useKeyboard() {
|
|||
}
|
||||
}, [rpcHidReady, sendKeyboardEventHidRpc, handleLegacyKeyboardReport, cancelKeepAlive]);
|
||||
|
||||
|
||||
// IMPORTANT: See the keyPressReportApiAvailable comment above for the reason this exists
|
||||
function simulateDeviceSideKeyHandlingForLegacyDevices(
|
||||
state: KeysDownState,
|
||||
|
|
@ -200,7 +197,9 @@ export default function useKeyboard() {
|
|||
// If we reach here it means we didn't find an empty slot or the key in the buffer
|
||||
if (overrun) {
|
||||
if (press) {
|
||||
console.warn(`keyboard buffer overflow current keys ${keys}, key: ${key} not added`);
|
||||
console.warn(
|
||||
`keyboard buffer overflow current keys ${keys}, key: ${key} not added`,
|
||||
);
|
||||
// Fill all key slots with ErrorRollOver (0x01) to indicate overflow
|
||||
keys.length = hidKeyBufferSize;
|
||||
keys.fill(hidErrorRollOver);
|
||||
|
|
@ -284,9 +283,8 @@ export default function useKeyboard() {
|
|||
// After the delay, the keys and modifiers are released and the next step is executed.
|
||||
// If a step has no keys or modifiers, it is treated as a delay-only step.
|
||||
// A small pause is added between steps to ensure that the device can process the events.
|
||||
const executeMacroRemote = useCallback(async (
|
||||
steps: MacroSteps,
|
||||
) => {
|
||||
const executeMacroRemote = useCallback(
|
||||
async (steps: MacroSteps) => {
|
||||
const macro: KeyboardMacroStep[] = [];
|
||||
|
||||
for (const [_, step] of steps.entries()) {
|
||||
|
|
@ -305,9 +303,12 @@ export default function useKeyboard() {
|
|||
}
|
||||
|
||||
sendKeyboardMacroEventHidRpc(macro);
|
||||
}, [sendKeyboardMacroEventHidRpc]);
|
||||
},
|
||||
[sendKeyboardMacroEventHidRpc],
|
||||
);
|
||||
|
||||
const executeMacroClientSide = useCallback(async (steps: MacroSteps) => {
|
||||
const executeMacroClientSide = useCallback(
|
||||
async (steps: MacroSteps) => {
|
||||
const promises: (() => Promise<void>)[] = [];
|
||||
|
||||
const ac = new AbortController();
|
||||
|
|
@ -335,7 +336,7 @@ export default function useKeyboard() {
|
|||
}
|
||||
await promise();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return await new Promise<void>((resolve, reject) => {
|
||||
// Set up abort listener
|
||||
|
|
@ -350,19 +351,24 @@ export default function useKeyboard() {
|
|||
ac.signal.removeEventListener("abort", abortListener);
|
||||
resolve();
|
||||
})
|
||||
.catch((error) => {
|
||||
.catch(error => {
|
||||
ac.signal.removeEventListener("abort", abortListener);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}, [sendKeystrokeLegacy, resetKeyboardState, setAbortController]);
|
||||
},
|
||||
[sendKeystrokeLegacy, resetKeyboardState, setAbortController],
|
||||
);
|
||||
|
||||
const executeMacro = useCallback(async (steps: MacroSteps) => {
|
||||
const executeMacro = useCallback(
|
||||
async (steps: MacroSteps) => {
|
||||
if (rpcHidReady) {
|
||||
return executeMacroRemote(steps);
|
||||
}
|
||||
return executeMacroClientSide(steps);
|
||||
}, [rpcHidReady, executeMacroRemote, executeMacroClientSide]);
|
||||
},
|
||||
[rpcHidReady, executeMacroRemote, executeMacroClientSide],
|
||||
);
|
||||
|
||||
const cancelExecuteMacro = useCallback(async () => {
|
||||
if (abortController.current) {
|
||||
|
|
@ -375,5 +381,11 @@ export default function useKeyboard() {
|
|||
cancelOngoingKeyboardMacroHidRpc();
|
||||
}, [rpcHidReady, cancelOngoingKeyboardMacroHidRpc, abortController]);
|
||||
|
||||
return { handleKeyPress, resetKeyboardState, executeMacro, cleanup, cancelExecuteMacro };
|
||||
return {
|
||||
handleKeyPress,
|
||||
resetKeyboardState,
|
||||
executeMacro,
|
||||
cleanup,
|
||||
cancelExecuteMacro,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,23 +1,11 @@
|
|||
import { useCallback } from "react";
|
||||
|
||||
import { useDeviceStore } from "@/hooks/stores";
|
||||
import { type JsonRpcResponse, RpcMethodNotFound, useJsonRpc } from "@/hooks/useJsonRpc";
|
||||
import { JsonRpcError, RpcMethodNotFound } from "@/hooks/useJsonRpc";
|
||||
import { getUpdateStatus, getLocalVersion as getLocalVersionRpc } from "@/utils/jsonrpc";
|
||||
import notifications from "@/notifications";
|
||||
import { m } from "@localizations/messages.js";
|
||||
|
||||
export interface VersionInfo {
|
||||
appVersion: string;
|
||||
systemVersion: string;
|
||||
}
|
||||
|
||||
export interface SystemVersionInfo {
|
||||
local: VersionInfo;
|
||||
remote?: VersionInfo;
|
||||
systemUpdateAvailable: boolean;
|
||||
appUpdateAvailable: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export function useVersion() {
|
||||
const {
|
||||
appVersion,
|
||||
|
|
@ -25,51 +13,40 @@ export function useVersion() {
|
|||
setAppVersion,
|
||||
setSystemVersion,
|
||||
} = useDeviceStore();
|
||||
const { send } = useJsonRpc();
|
||||
const getVersionInfo = useCallback(() => {
|
||||
return new Promise<SystemVersionInfo>((resolve, reject) => {
|
||||
send("getUpdateStatus", {}, (resp: JsonRpcResponse) => {
|
||||
if ("error" in resp) {
|
||||
notifications.error(m.updates_failed_check({ error: String(resp.error) }));
|
||||
reject(new Error("Failed to check for updates"));
|
||||
} else {
|
||||
const result = resp.result as SystemVersionInfo;
|
||||
|
||||
const getVersionInfo = useCallback(async () => {
|
||||
try {
|
||||
const result = await getUpdateStatus();
|
||||
setAppVersion(result.local.appVersion);
|
||||
setSystemVersion(result.local.systemVersion);
|
||||
|
||||
if (result.error) {
|
||||
notifications.error(m.updates_failed_check({ error: String(result.error) }));
|
||||
reject(new Error("Failed to check for updates"));
|
||||
} else {
|
||||
resolve(result);
|
||||
return result;
|
||||
} catch (error) {
|
||||
const jsonRpcError = error as JsonRpcError;
|
||||
notifications.error(m.updates_failed_check({ error: jsonRpcError.message }));
|
||||
throw jsonRpcError;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}, [send, setAppVersion, setSystemVersion]);
|
||||
|
||||
const getLocalVersion = useCallback(() => {
|
||||
return new Promise<VersionInfo>((resolve, reject) => {
|
||||
send("getLocalVersion", {}, (resp: JsonRpcResponse) => {
|
||||
if ("error" in resp) {
|
||||
console.log(resp.error)
|
||||
if (resp.error.code === RpcMethodNotFound) {
|
||||
console.warn("Failed to get device version, using legacy version");
|
||||
return getVersionInfo().then(result => resolve(result.local)).catch(reject);
|
||||
}
|
||||
console.error("Failed to get device version N", resp.error);
|
||||
notifications.error(m.updates_failed_get_device_version({ error: String(resp.error) }));
|
||||
reject(new Error("Failed to get device version"));
|
||||
} else {
|
||||
const result = resp.result as VersionInfo;
|
||||
}, [setAppVersion, setSystemVersion]);
|
||||
|
||||
const getLocalVersion = useCallback(async () => {
|
||||
try {
|
||||
const result = await getLocalVersionRpc();
|
||||
setAppVersion(result.appVersion);
|
||||
setSystemVersion(result.systemVersion);
|
||||
resolve(result);
|
||||
return result;
|
||||
} catch (error: unknown) {
|
||||
const jsonRpcError = error as JsonRpcError;
|
||||
|
||||
if (jsonRpcError.code === RpcMethodNotFound) {
|
||||
console.error("Failed to get local version, using legacy remote version");
|
||||
const result = await getVersionInfo();
|
||||
return result.local;
|
||||
}
|
||||
});
|
||||
});
|
||||
}, [send, setAppVersion, setSystemVersion, getVersionInfo]);
|
||||
|
||||
console.error("Failed to get device version", jsonRpcError);
|
||||
notifications.error(m.updates_failed_get_device_version({ error: jsonRpcError.message }));
|
||||
throw jsonRpcError;
|
||||
}
|
||||
}, [setAppVersion, setSystemVersion, getVersionInfo]);
|
||||
|
||||
return {
|
||||
getVersionInfo,
|
||||
|
|
|
|||
|
|
@ -4,12 +4,14 @@ import { useLocation, useNavigate } from "react-router";
|
|||
import { useJsonRpc } from "@hooks/useJsonRpc";
|
||||
import { UpdateState, useUpdateStore } from "@hooks/stores";
|
||||
import { useDeviceUiNavigation } from "@hooks/useAppNavigation";
|
||||
import { SystemVersionInfo, useVersion } from "@hooks/useVersion";
|
||||
import { useVersion } from "@hooks/useVersion";
|
||||
import { Button } from "@components/Button";
|
||||
import Card from "@components/Card";
|
||||
import LoadingSpinner from "@components/LoadingSpinner";
|
||||
import UpdatingStatusCard, { type UpdatePart} from "@components/UpdatingStatusCard";
|
||||
import UpdatingStatusCard, { type UpdatePart } from "@components/UpdatingStatusCard";
|
||||
import { m } from "@localizations/messages.js";
|
||||
import { sleep } from "@/utils";
|
||||
import { SystemVersionInfo } from "@/utils/jsonrpc";
|
||||
|
||||
export default function SettingsGeneralUpdateRoute() {
|
||||
const navigate = useNavigate();
|
||||
|
|
@ -134,13 +136,14 @@ function LoadingState({
|
|||
}, 0);
|
||||
|
||||
getVersionInfo()
|
||||
.then(versionInfo => {
|
||||
.then(async versionInfo => {
|
||||
// Add a small delay to ensure it's not just flickering
|
||||
return new Promise(resolve => setTimeout(() => resolve(versionInfo), 600));
|
||||
await sleep(600);
|
||||
return versionInfo
|
||||
})
|
||||
.then(versionInfo => {
|
||||
if (!signal.aborted) {
|
||||
onFinished(versionInfo as SystemVersionInfo);
|
||||
onFinished(versionInfo);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
|
|
|
|||
|
|
@ -677,6 +677,13 @@ export default function KvmIdRoute() {
|
|||
return;
|
||||
}
|
||||
|
||||
|
||||
// This is to prevent the otaState from handling page refreshes after an update
|
||||
// We've recently implemented a new general rebooting flow, so we don't need to handle this specific ota-rebooting case
|
||||
// However, with old devices, we wont get the `willReboot` message, so we need to keep this for backwards compatibility
|
||||
// only for the cloud version with an old device
|
||||
if (rebootState?.isRebooting) return;
|
||||
|
||||
const currentUrl = new URL(window.location.href);
|
||||
currentUrl.search = "";
|
||||
currentUrl.searchParams.set("updateSuccess", "true");
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import { KeySequence } from "@hooks/stores";
|
||||
import { getLocale } from '@localizations/runtime.js';
|
||||
import { getLocale , locales } from "@localizations/runtime.js";
|
||||
import { m } from "@localizations/messages.js";
|
||||
import { locales } from '@localizations/runtime.js';
|
||||
|
||||
export const formatters = {
|
||||
date: (date: Date, options?: Intl.DateTimeFormatOptions) =>
|
||||
|
|
@ -255,27 +254,41 @@ export function normalizeSortOrders(macros: KeySequence[]): KeySequence[] {
|
|||
...macro,
|
||||
sortOrder: index + 1,
|
||||
}));
|
||||
};
|
||||
}
|
||||
|
||||
type LocaleCode = typeof locales[number];
|
||||
type LocaleCode = (typeof locales)[number];
|
||||
|
||||
export function map_locale_code_to_name(currentLocale: LocaleCode, locale: string): [string, string] {
|
||||
export function map_locale_code_to_name(
|
||||
currentLocale: LocaleCode,
|
||||
locale: string,
|
||||
): [string, string] {
|
||||
// the first is the name in the current app locale (e.g. Inglese),
|
||||
// the second is the name in the language of the locale itself (e.g. English)
|
||||
switch (locale) {
|
||||
case '': return [m.locale_auto(), ""];
|
||||
case 'en': return [m.locale_en({}, { locale: currentLocale }), m.locale_en({}, { locale })];
|
||||
case 'da': return [m.locale_da({}, { locale: currentLocale }), m.locale_da({}, { locale })];
|
||||
case 'de': return [m.locale_de({}, { locale: currentLocale }), m.locale_de({}, { locale })];
|
||||
case 'es': return [m.locale_es({}, { locale: currentLocale }), m.locale_es({}, { locale })];
|
||||
case 'fr': return [m.locale_fr({}, { locale: currentLocale }), m.locale_fr({}, { locale })];
|
||||
case 'it': return [m.locale_it({}, { locale: currentLocale }), m.locale_it({}, { locale })];
|
||||
case 'nb': return [m.locale_nb({}, { locale: currentLocale }), m.locale_nb({}, { locale })];
|
||||
case 'sv': return [m.locale_sv({}, { locale: currentLocale }), m.locale_sv({}, { locale })];
|
||||
case 'zh': return [m.locale_zh({}, { locale: currentLocale }), m.locale_zh({}, { locale })];
|
||||
default: return [locale, ""];
|
||||
}
|
||||
case "":
|
||||
return [m.locale_auto(), ""];
|
||||
case "en":
|
||||
return [m.locale_en({}, { locale: currentLocale }), m.locale_en({}, { locale })];
|
||||
case "da":
|
||||
return [m.locale_da({}, { locale: currentLocale }), m.locale_da({}, { locale })];
|
||||
case "de":
|
||||
return [m.locale_de({}, { locale: currentLocale }), m.locale_de({}, { locale })];
|
||||
case "es":
|
||||
return [m.locale_es({}, { locale: currentLocale }), m.locale_es({}, { locale })];
|
||||
case "fr":
|
||||
return [m.locale_fr({}, { locale: currentLocale }), m.locale_fr({}, { locale })];
|
||||
case "it":
|
||||
return [m.locale_it({}, { locale: currentLocale }), m.locale_it({}, { locale })];
|
||||
case "nb":
|
||||
return [m.locale_nb({}, { locale: currentLocale }), m.locale_nb({}, { locale })];
|
||||
case "sv":
|
||||
return [m.locale_sv({}, { locale: currentLocale }), m.locale_sv({}, { locale })];
|
||||
case "zh":
|
||||
return [m.locale_zh({}, { locale: currentLocale }), m.locale_zh({}, { locale })];
|
||||
default:
|
||||
return [locale, ""];
|
||||
}
|
||||
}
|
||||
|
||||
export function deleteCookie(name: string, domain?: string, path = "/") {
|
||||
const domainPart = domain ? `; domain=${domain}` : "";
|
||||
|
|
@ -284,3 +297,7 @@ export function deleteCookie(name: string, domain?: string, path = "/") {
|
|||
// fallback: set an expires in the past for older agents
|
||||
document.cookie = `${name}=; path=${path}; expires=Thu, 01 Jan 1970 00:00:00 GMT${domainPart}`;
|
||||
}
|
||||
|
||||
export function sleep(ms: number): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,18 @@
|
|||
import { useRTCStore } from "@/hooks/stores";
|
||||
import { sleep } from "@/utils";
|
||||
|
||||
// JSON-RPC utility for use outside of React components
|
||||
|
||||
export interface JsonRpcCallOptions {
|
||||
method: string;
|
||||
params?: unknown;
|
||||
timeout?: number;
|
||||
attemptTimeoutMs?: number;
|
||||
maxAttempts?: number;
|
||||
}
|
||||
|
||||
export interface JsonRpcCallResponse {
|
||||
export interface JsonRpcCallResponse<T = unknown> {
|
||||
jsonrpc: string;
|
||||
result?: unknown;
|
||||
result?: T;
|
||||
error?: {
|
||||
code: number;
|
||||
message: string;
|
||||
|
|
@ -20,16 +23,28 @@ export interface JsonRpcCallResponse {
|
|||
|
||||
let rpcCallCounter = 0;
|
||||
|
||||
export function callJsonRpc(options: JsonRpcCallOptions): Promise<JsonRpcCallResponse> {
|
||||
return new Promise((resolve, reject) => {
|
||||
// Access the RTC store directly outside of React context
|
||||
const rpcDataChannel = useRTCStore.getState().rpcDataChannel;
|
||||
// Helper: wait for RTC data channel to be ready
|
||||
async function waitForRtcReady(signal: AbortSignal): Promise<RTCDataChannel> {
|
||||
const pollInterval = 100;
|
||||
|
||||
if (!rpcDataChannel || rpcDataChannel.readyState !== "open") {
|
||||
reject(new Error("RPC data channel not available"));
|
||||
return;
|
||||
while (!signal.aborted) {
|
||||
const state = useRTCStore.getState();
|
||||
if (state.rpcDataChannel?.readyState === "open") {
|
||||
return state.rpcDataChannel;
|
||||
}
|
||||
await sleep(pollInterval);
|
||||
}
|
||||
|
||||
throw new Error("RTC readiness check aborted");
|
||||
}
|
||||
|
||||
// Helper: send RPC request and wait for response
|
||||
async function sendRpcRequest<T>(
|
||||
rpcDataChannel: RTCDataChannel,
|
||||
options: JsonRpcCallOptions,
|
||||
signal: AbortSignal,
|
||||
): Promise<JsonRpcCallResponse<T>> {
|
||||
return new Promise((resolve, reject) => {
|
||||
rpcCallCounter++;
|
||||
const requestId = `rpc_${Date.now()}_${rpcCallCounter}`;
|
||||
|
||||
|
|
@ -40,32 +55,93 @@ export function callJsonRpc(options: JsonRpcCallOptions): Promise<JsonRpcCallRes
|
|||
id: requestId,
|
||||
};
|
||||
|
||||
const timeout = options.timeout || 5000;
|
||||
let timeoutId: number | undefined; // eslint-disable-line prefer-const
|
||||
|
||||
const messageHandler = (event: MessageEvent) => {
|
||||
try {
|
||||
const response = JSON.parse(event.data) as JsonRpcCallResponse;
|
||||
const response = JSON.parse(event.data) as JsonRpcCallResponse<T>;
|
||||
if (response.id === requestId) {
|
||||
clearTimeout(timeoutId);
|
||||
rpcDataChannel.removeEventListener("message", messageHandler);
|
||||
cleanup();
|
||||
resolve(response);
|
||||
}
|
||||
} catch (error) {
|
||||
} catch {
|
||||
// Ignore parse errors from other messages
|
||||
}
|
||||
};
|
||||
|
||||
timeoutId = setTimeout(() => {
|
||||
rpcDataChannel.removeEventListener("message", messageHandler);
|
||||
reject(new Error(`JSON-RPC call timed out after ${timeout}ms`));
|
||||
}, timeout);
|
||||
const abortHandler = () => {
|
||||
cleanup();
|
||||
reject(new Error("Request aborted"));
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
rpcDataChannel.removeEventListener("message", messageHandler);
|
||||
signal.removeEventListener("abort", abortHandler);
|
||||
};
|
||||
|
||||
signal.addEventListener("abort", abortHandler);
|
||||
rpcDataChannel.addEventListener("message", messageHandler);
|
||||
rpcDataChannel.send(JSON.stringify(request));
|
||||
});
|
||||
}
|
||||
|
||||
// Function overloads for better typing
|
||||
export function callJsonRpc<T>(
|
||||
options: JsonRpcCallOptions,
|
||||
): Promise<JsonRpcCallResponse<T> & { result: T }>;
|
||||
export function callJsonRpc(
|
||||
options: JsonRpcCallOptions,
|
||||
): Promise<JsonRpcCallResponse<unknown>>;
|
||||
export async function callJsonRpc<T = unknown>(
|
||||
options: JsonRpcCallOptions,
|
||||
): Promise<JsonRpcCallResponse<T>> {
|
||||
const maxAttempts = options.maxAttempts ?? 1;
|
||||
const timeout = options.attemptTimeoutMs || 5000;
|
||||
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
const abortController = new AbortController();
|
||||
const timeoutId = setTimeout(() => abortController.abort(), timeout);
|
||||
|
||||
// Exponential backoff for retries that starts at 500ms up to a maximum of 10 seconds
|
||||
const backoffMs = Math.min(500 * Math.pow(2, attempt), 10000);
|
||||
|
||||
try {
|
||||
// Wait for RTC readiness
|
||||
const rpcDataChannel = await waitForRtcReady(abortController.signal);
|
||||
|
||||
// Send RPC request and wait for response
|
||||
const response = await sendRpcRequest<T>(
|
||||
rpcDataChannel,
|
||||
options,
|
||||
abortController.signal,
|
||||
);
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
// Retry on error if attempts remain
|
||||
if (response.error && attempt < maxAttempts - 1) {
|
||||
await sleep(backoffMs);
|
||||
continue;
|
||||
}
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
// Retry on timeout/error if attempts remain
|
||||
if (attempt < maxAttempts - 1) {
|
||||
await sleep(backoffMs);
|
||||
continue;
|
||||
}
|
||||
|
||||
throw error instanceof Error
|
||||
? error
|
||||
: new Error(`JSON-RPC call failed after ${timeout}ms`);
|
||||
}
|
||||
}
|
||||
|
||||
// Should never reach here due to loop logic, but TypeScript needs this
|
||||
throw new Error("Unexpected error in callJsonRpc");
|
||||
}
|
||||
|
||||
// Specific network settings API calls
|
||||
export async function getNetworkSettings() {
|
||||
const response = await callJsonRpc({ method: "getNetworkSettings" });
|
||||
|
|
@ -101,3 +177,35 @@ export async function renewDHCPLease() {
|
|||
}
|
||||
return response.result;
|
||||
}
|
||||
|
||||
export interface VersionInfo {
|
||||
appVersion: string;
|
||||
systemVersion: string;
|
||||
}
|
||||
|
||||
export interface SystemVersionInfo {
|
||||
local: VersionInfo;
|
||||
remote?: VersionInfo;
|
||||
systemUpdateAvailable: boolean;
|
||||
appUpdateAvailable: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export async function getUpdateStatus() {
|
||||
const response = await callJsonRpc<SystemVersionInfo>({
|
||||
method: "getUpdateStatus",
|
||||
// This function calls our api server to see if there are any updates available.
|
||||
// It can be called on page load right after a restart, so we need to give it time to
|
||||
// establish a connection to the api server.
|
||||
maxAttempts: 6,
|
||||
});
|
||||
|
||||
if (response.error) throw response.error;
|
||||
return response.result;
|
||||
}
|
||||
|
||||
export async function getLocalVersion() {
|
||||
const response = await callJsonRpc<VersionInfo>({ method: "getLocalVersion" });
|
||||
if (response.error) throw response.error;
|
||||
return response.result;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue