File size: 7,761 Bytes
fa9c65f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | import type { AppContext, AppModule } from '@/app/app-context';
import { invokeTauri } from '@/services/tauri-bridge';
import { trackUpdateShown, trackUpdateClicked, trackUpdateDismissed } from '@/services/analytics';
import { escapeHtml } from '@/utils/sanitize';
import { getDismissed, setDismissed } from '@/utils/cross-domain-storage';
import { setTrustedHtml, trustedHtml } from '@/utils/dom-utils';
interface DesktopRuntimeInfo {
os: string;
arch: string;
}
type UpdaterOutcome = 'no_update' | 'update_available' | 'open_failed' | 'fetch_failed';
type DesktopBuildVariant = 'full' | 'tech' | 'finance';
const DESKTOP_BUILD_VARIANT: DesktopBuildVariant = (
import.meta.env.VITE_VARIANT === 'tech' || import.meta.env.VITE_VARIANT === 'finance'
? import.meta.env.VITE_VARIANT
: 'full'
);
export class DesktopUpdater implements AppModule {
private ctx: AppContext;
private updateCheckIntervalId: ReturnType<typeof setInterval> | null = null;
private readonly UPDATE_CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000;
constructor(ctx: AppContext) {
this.ctx = ctx;
}
init(): void {
this.setupUpdateChecks();
}
destroy(): void {
if (this.updateCheckIntervalId) {
clearInterval(this.updateCheckIntervalId);
this.updateCheckIntervalId = null;
}
}
private setupUpdateChecks(): void {
if (!this.ctx.isDesktopApp || this.ctx.isDestroyed) return;
setTimeout(() => {
if (this.ctx.isDestroyed) return;
void this.checkForUpdate();
}, 5000);
if (this.updateCheckIntervalId) {
clearInterval(this.updateCheckIntervalId);
}
this.updateCheckIntervalId = setInterval(() => {
if (this.ctx.isDestroyed) return;
void this.checkForUpdate();
}, this.UPDATE_CHECK_INTERVAL_MS);
}
private logUpdaterOutcome(outcome: UpdaterOutcome, context: Record<string, unknown> = {}): void {
const logger = outcome === 'open_failed' || outcome === 'fetch_failed'
? console.warn
: console.info;
logger('[updater]', outcome, context);
}
private getDesktopBuildVariant(): DesktopBuildVariant {
return DESKTOP_BUILD_VARIANT;
}
private async checkForUpdate(): Promise<void> {
try {
const res = await fetch('https://api.worldmonitor.app/api/version', {
signal: AbortSignal.timeout(8000),
});
if (!res.ok) {
this.logUpdaterOutcome('fetch_failed', { status: res.status });
return;
}
const data = await res.json();
const remote = data.version as string;
if (!remote) {
this.logUpdaterOutcome('fetch_failed', { reason: 'missing_remote_version' });
return;
}
const current = __APP_VERSION__;
if (!this.isNewerVersion(remote, current)) {
this.logUpdaterOutcome('no_update', { current, remote });
return;
}
const dismissKey = `wm-update-dismissed-${remote}`;
if (getDismissed(dismissKey)) {
this.logUpdaterOutcome('update_available', { current, remote, dismissed: true });
return;
}
const releaseUrl = typeof data.url === 'string' && data.url
? data.url
: 'https://github.com/koala73/worldmonitor/releases/latest';
this.logUpdaterOutcome('update_available', { current, remote, dismissed: false });
trackUpdateShown(current, remote);
await this.showUpdateToast(remote, releaseUrl);
} catch (error) {
this.logUpdaterOutcome('fetch_failed', {
error: error instanceof Error ? error.message : String(error),
});
}
}
private isNewerVersion(remote: string, current: string): boolean {
const r = remote.split('.').map(Number);
const c = current.split('.').map(Number);
for (let i = 0; i < Math.max(r.length, c.length); i++) {
const rv = r[i] ?? 0;
const cv = c[i] ?? 0;
if (rv > cv) return true;
if (rv < cv) return false;
}
return false;
}
private mapDesktopDownloadPlatform(os: string, arch: string): string | null {
const normalizedOs = os.toLowerCase();
const normalizedArch = arch.toLowerCase()
.replace('amd64', 'x86_64')
.replace('x64', 'x86_64')
.replace('arm64', 'aarch64');
if (normalizedOs === 'windows') {
return normalizedArch === 'x86_64' ? 'windows-msi' : null;
}
if (normalizedOs === 'macos' || normalizedOs === 'darwin') {
if (normalizedArch === 'aarch64') return 'macos-arm64';
if (normalizedArch === 'x86_64') return 'macos-x64';
return null;
}
if (normalizedOs === 'linux') {
if (normalizedArch === 'x86_64') return 'linux-appimage';
if (normalizedArch === 'aarch64') return 'linux-appimage-arm64';
return null;
}
return null;
}
private async resolveUpdateDownloadUrl(releaseUrl: string): Promise<string> {
try {
const runtimeInfo = await invokeTauri<DesktopRuntimeInfo>('get_desktop_runtime_info');
const platform = this.mapDesktopDownloadPlatform(runtimeInfo.os, runtimeInfo.arch);
if (platform) {
const variant = this.getDesktopBuildVariant();
return `https://api.worldmonitor.app/api/download?platform=${platform}&variant=${variant}`;
}
} catch {
// Silent fallback to release page when desktop runtime info is unavailable.
}
return releaseUrl;
}
private async showUpdateToast(version: string, releaseUrl: string): Promise<void> {
const existing = document.querySelector<HTMLElement>('.update-toast');
if (existing?.dataset.version === version) return;
existing?.remove();
const url = await this.resolveUpdateDownloadUrl(releaseUrl);
const toast = document.createElement('div');
toast.className = 'update-toast';
toast.dataset.version = version;
setTrustedHtml(toast, trustedHtml(`
<div class="update-toast-icon">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
<polyline points="7 10 12 15 17 10"/>
<line x1="12" y1="15" x2="12" y2="3"/>
</svg>
</div>
<div class="update-toast-body">
<div class="update-toast-title">Update Available</div>
<div class="update-toast-detail">v${escapeHtml(__APP_VERSION__)} \u2192 v${escapeHtml(version)}</div>
</div>
<button class="update-toast-action" data-action="download">Download</button>
<button class="update-toast-dismiss" data-action="dismiss" aria-label="Dismiss">\u00d7</button>
`, "legacy direct innerHTML migration"));
const dismissToast = () => {
setDismissed(`wm-update-dismissed-${version}`);
toast.classList.remove('visible');
setTimeout(() => toast.remove(), 300);
};
toast.addEventListener('click', (e) => {
const target = e.target as HTMLElement;
const action = target.closest<HTMLElement>('[data-action]')?.dataset.action;
if (action === 'download') {
trackUpdateClicked(version);
if (this.ctx.isDesktopApp) {
void invokeTauri<void>('open_url', { url }).catch((error) => {
this.logUpdaterOutcome('open_failed', { url, error: error instanceof Error ? error.message : String(error) });
window.open(url, '_blank', 'noopener,noreferrer');
});
} else {
window.open(url, '_blank', 'noopener,noreferrer');
}
dismissToast();
} else if (action === 'dismiss') {
trackUpdateDismissed(version);
dismissToast();
}
});
document.body.appendChild(toast);
requestAnimationFrame(() => {
requestAnimationFrame(() => toast.classList.add('visible'));
});
}
}
|