HRM-10/HRM.UI/ClientApp/src/app/version-check.service.ts

105 lines
4.3 KiB
TypeScript
Raw Normal View History

2026-11-03 13:06:00 +06:00
import { Injectable, OnDestroy } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { interval, Subscription, of, BehaviorSubject } from 'rxjs';
import { switchMap, catchError, map } from 'rxjs/operators';
import { HRMNotificationService } from './app.notification.service';
@Injectable({ providedIn: 'root' })
export class VersionCheckService implements OnDestroy {
private currentVersion: string | null = null; // Stores the version that was active when the app first loaded
private subscription: Subscription | null = null; // Holds the polling subscription so we can clean it up later
private readonly CHECK_INTERVAL_MS = 5 * 60 * 1000; // How often to check the server for a new version (every 3 minutes)
private isPromptShowing = false; // Prevents showing multiple reload prompts at the same time
public currentVersion$ = new BehaviorSubject<string>('...'); // Public observable — any component (footer, login) can subscribe to get version
constructor(
private http: HttpClient,
private notificationService: HRMNotificationService // Inject existing notification service
) {}
/**
* Starts the version polling process.
* Call this once from AppComponent.ngOnInit().
* @param baseHref - The base href of the app (e.g. '/LuminousSelfService/' or '/')
*/
startChecking(baseHref: string): void {
// On app load, fetch and store the current deployed version
this.fetchVersion(baseHref).subscribe(v => {
if (v) {
this.currentVersion = v;
this.currentVersion$.next(v); // broadcast to all subscribers (footer, login, etc.)
console.log('[VersionCheck] App loaded with version:', v);
}
});
// Poll the server every 3 minutes to check if a new version has been deployed
this.subscription = interval(this.CHECK_INTERVAL_MS)
.pipe(
// On each tick, fetch the latest version.json from the server
switchMap(() => this.fetchVersion(baseHref)),
// If the request fails (e.g. offline), emit null and keep polling
catchError(() => of(null))
)
.subscribe(serverVersion => {
const isNewVersionAvailable =
serverVersion && // server returned a valid version
this.currentVersion && // we have a version to compare against
serverVersion !== this.currentVersion; // versions are different
if (isNewVersionAvailable && !this.isPromptShowing) {
console.log('[VersionCheck] New version detected:', serverVersion);
this.promptUserToReload();
}
});
}
/**
* Fetches version.json from the server.
* Adds a timestamp query param (?t=...) to bypass browser cache
* so we always get the latest file, not a cached copy.
*/
private fetchVersion(baseHref: string) {
const url = `${baseHref}version.json?t=${Date.now()}`;
return this.http
.get<{ version: string; buildTime: string }>(url, {
headers: new HttpHeaders({ 'Cache-Control': 'no-cache' })
})
.pipe(
// We only need the version string, not the full object
map(res => res.version),
// If the request errors out, return null so polling continues
catchError(() => of(null))
);
}
/**
* Shows a confirmation dialog using HRMNotificationService.
* If the user confirms, the page reloads and loads the latest version.
* If the user cancels, the prompt can appear again on the next polling cycle.
*/
private promptUserToReload(): void {
this.isPromptShowing = true;
// Using your existing HRMNotificationService instead of browser confirm()
this.notificationService
.showActiveConfirm('New Version Available', 'A new version has been deployed. Reload now to get the latest updates?')
.then((isConfirmed) => {
if (isConfirmed) {
// Force a hard reload — bypasses cache and loads fresh files from server
window.location.reload();
} else {
// User dismissed the prompt — allow it to show again on the next version check
this.isPromptShowing = false;
}
});
}
/**
* Cleans up the polling subscription when the service is destroyed.
* Prevents memory leaks.
*/
ngOnDestroy(): void {
this.subscription?.unsubscribe();
}
}