Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

UI updates: Improvements offline consistency (#1172)

Martin Peeters0b06bb6ddd8f
diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.json
index a0e758365..3aa7405e6 100644
--- a/manager/src/web/shared/locales/en/or.json
+++ b/manager/src/web/shared/locales/en/or.json
@@ -331,7 +331,7 @@
"host": "Hostname",
"errorOccurred": "An error has occurred",
"sendFailed": "Send failed",
- "youAreOffline": "You are offline",
+ "youAreOffline": "Lost connection to the server",
"checkConnection": "Please check your connection",
"retryingConnection": "Retrying in {{seconds}} seconds",
"reconnecting": "Reconnecting",
diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.json
index 8d59c89fc..195526ecd 100644
--- a/manager/src/web/shared/locales/nl/or.json
+++ b/manager/src/web/shared/locales/nl/or.json
@@ -331,7 +331,7 @@
"host": "Hostname",
"errorOccurred": "Er is een fout opgetreden",
"sendFailed": "Verzenden mislukt",
- "youAreOffline": "Geen internet",
+ "youAreOffline": "Verbinding verloren met de server",
"checkConnection": "Controleer je internetverbinding",
"retryingConnection": "Opnieuw proberen na {{seconds}} seconden",
"reconnecting": "Verbinden",
diff --git a/ui/component/core/src/event.ts b/ui/component/core/src/event.ts
index f789c9597..356151c3f 100644
--- a/ui/component/core/src/event.ts
+++ b/ui/component/core/src/event.ts
@@ -12,7 +12,6 @@ import {
EventRequestResponseWrapper,
EventSubscription,
ReadAssetsEvent,
- ReadAttributeEvent,
SharedEvent,
TriggeredEventSubscription
} from "@openremote/model";
@@ -20,7 +19,8 @@ import {
export enum EventProviderStatus {
DISCONNECTED = "DISCONNECTED",
CONNECTED = "CONNECTED",
- CONNECTING = "CONNECTING"
+ CONNECTING = "CONNECTING",
+ RECONNECT_FAILED = "RECONNECT_FAILED"
}
export interface EventProvider {
@@ -159,6 +159,7 @@ abstract class EventProviderImpl implements EventProvider {
}
public disconnect(): void {
+ console.debug("Disconnecting from event service: " + this.endpointUrl);
if (this._disconnectRequested) {
return;
}
@@ -564,9 +565,11 @@ abstract class EventProviderImpl implements EventProvider {
this.connect().then(connected => {
if (!connected) {
+ this._onStatusChanged(EventProviderStatus.RECONNECT_FAILED);
this._scheduleReconnect();
}
}).catch(error => {
+ this._onStatusChanged(EventProviderStatus.RECONNECT_FAILED);
this._scheduleReconnect();
});
}, this._reconnectDelayMillis);
@@ -625,6 +628,10 @@ export class WebSocketEventProvider extends EventProviderImpl {
this._webSocket = new WebSocket(authorisedUrl);
this._connectDeferred = new Deferred();
+ if(manager.isTokenExpired()) {
+ this._connectDeferred.resolve(false);
+ }
+
this._webSocket!.onopen = () => {
if (this._connectDeferred) {
const deferred = this._connectDeferred;
@@ -706,7 +713,7 @@ export class WebSocketEventProvider extends EventProviderImpl {
}
protected _doDisconnect(): void {
- this._webSocket!.close();
+ this._webSocket?.close();
this._subscribeDeferred = null;
this._repliesDeferred.clear();
}
diff --git a/ui/component/core/src/index.ts b/ui/component/core/src/index.ts
index 0a523cc8f..923b4585a 100644
--- a/ui/component/core/src/index.ts
+++ b/ui/component/core/src/index.ts
@@ -6,17 +6,9 @@ import {EventProvider, EventProviderFactory, EventProviderStatus, WebSocketEvent
import i18next, {InitOptions} from "i18next";
import i18nextBackend from "i18next-http-backend";
import moment from "moment";
-import {
- AssetModelUtil,
- ConsoleAppConfig,
- MapType,
- Role,
- User,
- UsernamePassword,
-} from "@openremote/model";
+import {AssetModelUtil, Auth, ConsoleAppConfig, EventProviderType, ManagerConfig, MapType, Role, User, UsernamePassword} from "@openremote/model";
import * as Util from "./util";
-import {IconSets, createSvgIconSet, createMdiIconSet, OrIconSet} from "@openremote/or-icon";
-import { Auth, EventProviderType, ManagerConfig } from "@openremote/model/lib";
+import {createMdiIconSet, createSvgIconSet, IconSets, OrIconSet} from "@openremote/or-icon";
// Re-exports
export {Util};
@@ -66,8 +58,11 @@ export enum OREvent {
ONLINE = "ONLINE",
OFFLINE = "OFFLINE",
CONNECTING = "CONNECTING",
+ RECONNECT_FAILED = "RECONNECT_FAILED",
CONSOLE_INIT = "CONSOLE_INIT",
CONSOLE_READY = "CONSOLE_READY",
+ CONSOLE_VISIBLE = "CONSOLE_VISIBLE",
+ CONSOLE_HIDDEN = "CONSOLE_HIDDEN",
TRANSLATE_INIT = "TRANSLATE_INIT",
TRANSLATE_LANGUAGE_CHANGED = "TRANSLATE_LANGUAGE_CHANGED",
DISPLAY_REALM_CHANGED = "DISPLAY_REALM_CHANGED"
@@ -276,8 +271,8 @@ export class Manager implements EventProviderFactory {
private _error?: ORError;
private _config!: ManagerConfig;
private _authenticated: boolean = false;
- private _disconnected: boolean = false;
- private _reconnectInterval?: number;
+ private _authDisconnected: boolean = false;
+ private _authReconnectTimeout?: number;
private _ready: boolean = false;
private _readyCallback?: () => PromiseLike<any>;
private _name: string = "";
@@ -295,6 +290,7 @@ export class Manager implements EventProviderFactory {
private _console!: Console;
private _consoleAppConfig?: ConsoleAppConfig;
private _events?: EventProvider;
+ private _eventsDisconnected: boolean = false;
private _displayRealm?: string;
public isManagerSameOrigin(): boolean {
@@ -590,58 +586,165 @@ export class Manager implements EventProviderFactory {
return connected;
}
- // Timer that runs the reconnect logic every X milliseconds
- // It automatically clears the interval when the reconnect is successful.
- protected _runReconnectTimer(timeout = 10000) {
- if(!this._reconnectInterval) {
- this._reconnectInterval = window.setInterval(() => {
- console.log("Attempting to reconnect...");
- this._attemptReconnect().then((disconnected) => {
+ // Public method for reconnecting
+ public reconnect(force = false) {
+ if(this._authDisconnected || force) {
+ this._runAuthReconnectTimer();
+ }
+ if(this._eventsDisconnected || force) {
+ this._tryReconnectEvents();
+ }
+ }
+
+ // A timer that runs that tries 'reconnecting' to the authentication service logic every X milliseconds.
+ // This timer increases by 20% with every reconnect attempt, with a maximum of 'timeoutMax' which is 20 seconds by default.
+ // Reconnecting in this case means; trying to update the token. See _tryUpdateAccessToken() for more details.
+ // It will emit OREvent.RECONNECT_FAILED if it failed to.
+ protected _runAuthReconnectTimer(timeout = 5000, timeoutMax = 20000) {
+ if(!this._authReconnectTimeout) {
+ const reconnectAuthFunc = () => {
+ this._tryUpdateAccessToken().then((disconnected) => {
if(!disconnected) {
- clearInterval(this._reconnectInterval);
- delete this._reconnectInterval;
+ this._finishAuthReconnectTimer(true);
+ } else {
+ timeout = Math.min(timeoutMax, Math.round(timeout * 1.2)); // gradually increase the timer
+ console.debug(`Authentication service reconnect failed. Trying again in ${timeout} milliseconds...`)
+ this._authReconnectTimeout = window.setTimeout(reconnectAuthFunc, timeout); // continue timer
+ this._emitEvent(OREvent.RECONNECT_FAILED);
}
+
+ }).catch((e) => {
+ // It is very unlikely that an exception is thrown here, but we should finish the timer if it does
+ console.error(e);
+ this._finishAuthReconnectTimer(false);
+ })
+ };
+ // Start reconnect timer by triggering it once
+ reconnectAuthFunc();
+
+
+ // If a timer is already running, just try to update the access token directly without initiating a timer.
+ } else {
+ this._tryUpdateAccessToken();
+ }
+ }
+
+
+ // Method that clears the Timeout and sets auth disconnected state.
+ protected _finishAuthReconnectTimer(success: boolean) {
+ if(this._authReconnectTimeout) {
+ clearTimeout(this._authReconnectTimeout);
+ delete this._authReconnectTimeout;
+ if(success) {
+ this._setAuthDisconnected(false);
+ }
+ }
+ }
+
+
+ // Checks whether keycloak is reachable using a simple HTTP request.
+ // Since the keycloak JS adapter doesn't give us details of the HTTP responses they get, we test it manually using this.
+ // Resolves or throws exception.
+ protected async isKeycloakReachable(): Promise<void> {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 2000);
+ try {
+ await fetch(this._config.keycloakUrl! + "/health/ready", {method: 'HEAD', mode: 'no-cors', signal: controller.signal});
+ return Promise.resolve();
+ } catch (e) {
+ return Promise.reject(e);
+ } finally {
+ clearTimeout(timeout);
+ }
+ }
+
+ // Function that tries to update the token, whilst making sure the authentication service is available.
+ // It first checks the connection to keycloak, and then tries to update the access token.
+ // Mostly used during "reconnect" logic, since it isn't necessary to 'double check' service availability in most cases.
+ // TODO: Currently only applies to Keycloak, not implemented for basic auth.
+ protected async _tryUpdateAccessToken(): Promise<boolean> {
+ let authOffline = false;
+ if(this.isKeycloak()) {
+
+ console.debug("Attempting to update keycloak access token...");
+ this._emitEvent(OREvent.CONNECTING); // emit event every time a reconnect attempt is made
+
+ // Check if keycloak service is available / can be accessed.
+ await this.isKeycloakReachable().catch(() => {
+ authOffline = true;
+ console.error("Could not reach keycloak service! Aborting token update.");
+ });
+ if(!authOffline) {
+
+ // Update token
+ await this.updateKeycloakAccessToken().catch((e) => {
+ authOffline = true;
+ console.error(e);
});
- }, timeout);
+ }
}
+
+ // Update _authDisconnected respectively
+ this._setAuthDisconnected(authOffline);
+
+ return authOffline;
}
- protected async _attemptReconnect(): Promise<boolean> {
- this._setDisconnected(true);
- this._emitEvent(OREvent.CONNECTING); // emit event every time a reconnect attempt is made
+ // Function that tries to reconnect the EventProvider (such as WebSocket)
+ protected _tryReconnectEvents() {
+ if(this.events?.status !== EventProviderStatus.CONNECTED) {
+
+ // If disconnected, proceed in trying to reconnect EventProvider...
+ if(this.events?.status === EventProviderStatus.DISCONNECTED) {
+ this._connectEvents();
+ }
+
+ // If already "connecting" the EventProvider, wait for attempt to finish, otherwise execute connectEvents() directly.
+ // We subscribe to its status change, and unsubscribe after we get a callback that it got DISCONNECTED. (or a timeout of 4 seconds has gone by)
+ else if(this.events?.status === EventProviderStatus.CONNECTING) {
+ const callback = (status: EventProviderStatus) => {
+ if (status === EventProviderStatus.DISCONNECTED) {
+ this.events?.unsubscribeStatusChange(callback);
+ this._connectEvents();
+ }
+ };
+ // Subscribe to status change, and add timeout of 4 seconds to automatically unsubscribe.
+ this.events.subscribeStatusChange(callback);
+ setTimeout(() => {
+ this.events?.unsubscribeStatusChange(callback)
+ }, 4000);
- // Attempt keycloak check, if applicable
- let keycloakOffline = false;
- if(this._keycloak !== undefined) {
- try {
- // Before updating keycloak token, check whether Keycloak is UP using a simple HEAD request
- await fetch(this._config.keycloakUrl! + "/health/ready", {method: 'HEAD', mode: 'no-cors'});
- await this.updateKeycloakAccessToken();
- } catch (e) {
- keycloakOffline = true;
- console.error("Could not reach keycloak server.");
}
}
+ }
- const offline = (keycloakOffline)
- this._setDisconnected(offline);
- return offline;
+ // Function that connects the EventProvider.
+ protected _connectEvents() {
+ if(this.events?.status === EventProviderStatus.DISCONNECTED) {
+ this.events!.connect().catch((e) => {
+ console.error(`Failed to connect EventProvider.`);
+ console.error(e);
+ });
+ } else {
+ console.warn("Tried to connect EventProvider, but it wasn't disconnected!");
+ }
}
protected _onEventProviderStatusChanged(status: EventProviderStatus) {
switch (status) {
case EventProviderStatus.DISCONNECTED:
- console.log("Event provider disconnected.");
- this._emitEvent(OREvent.OFFLINE);
+ this._setEventDisconnected(true);
break;
case EventProviderStatus.CONNECTED:
- console.log("Event provider connected.")
- this._emitEvent(OREvent.ONLINE);
+ this._setEventDisconnected(false);
break;
case EventProviderStatus.CONNECTING:
this._emitEvent(OREvent.CONNECTING);
break;
+ case EventProviderStatus.RECONNECT_FAILED:
+ this._emitEvent(OREvent.RECONNECT_FAILED);
+ break;
}
}
@@ -834,7 +937,7 @@ export class Manager implements EventProviderFactory {
}
public hasRealmRole(role: string) {
- return this._keycloak && this._keycloak.hasRealmRole(role);
+ return this.isKeycloak() && this._keycloak!.hasRealmRole(role);
}
public hasRole(role: string, client: string = this._config.clientId!) {
@@ -853,8 +956,8 @@ export class Manager implements EventProviderFactory {
}
public getKeycloakToken(): string | undefined {
- if (this._keycloak) {
- return this._keycloak.token;
+ if (this.isKeycloak()) {
+ return this._keycloak!.token;
}
return undefined;
}
@@ -863,6 +966,16 @@ export class Manager implements EventProviderFactory {
return this._basicIdentity ? this._basicIdentity.token : undefined;
}
+ // Checking (manually) if token is invalid by verifying expiry date.
+ // By default, using a margin / minimum validity of 2 seconds
+ public isTokenExpired(margin = 2000): boolean {
+ if(this.isKeycloak()) {
+ return (this._keycloak!.tokenParsed.exp <= moment().add(margin, "milliseconds").unix());
+ } else {
+ return !this._basicIdentity?.token; // TODO: Update this to check validity of JWT token manually
+ }
+ }
+
public getRealm(): string | undefined {
if (this._config) {
return this._config.realm;
@@ -921,6 +1034,8 @@ export class Manager implements EventProviderFactory {
if (keycloakPromise) {
keycloakPromise(true);
}
+ // clear auth reconnect timer after success
+ this._finishAuthReconnectTimer(true);
};
this._keycloak!.onAuthError = () => {
@@ -928,10 +1043,8 @@ export class Manager implements EventProviderFactory {
};
this._keycloak!.onAuthRefreshError = () => {
- console.log("Failed to refresh the access token.")
- if(this._keycloak?.isTokenExpired()) {
- this._runReconnectTimer();
- }
+ console.debug("Keycloak failed to refresh the access token.");
+ this._setAuthDisconnected(true);
}
try {
@@ -959,8 +1072,10 @@ export class Manager implements EventProviderFactory {
}
this._keycloakUpdateTokenInterval = window.setInterval(() => {
// only try to update token when online, otherwise the reconnect logic (this._attemptReconnect()) will try this
- if(!this._disconnected) {
- this.updateKeycloakAccessToken();
+ if(!this._authDisconnected) {
+ this.updateKeycloakAccessToken().catch(() => {
+ console.error("Could not update keycloak access token during regular interval.");
+ });
}
}, 10000);
this._onAuthenticated();
@@ -981,11 +1096,23 @@ export class Manager implements EventProviderFactory {
}
protected async updateKeycloakAccessToken(): Promise<boolean | void> {
+
// Access token must be good for X more seconds, should be half of Constants.ACCESS_TOKEN_LIFESPAN_SECONDS
- const tokenRefreshed = await this._keycloak!.updateToken(30);
- // If refreshed from server, it means the refresh token was still good for another access token
- console.debug("Access token update success, refreshed from server: " + tokenRefreshed);
- return tokenRefreshed;
+ // TODO: Improve this, see https://github.com/openremote/openremote/issues/1233
+ const promise = this._keycloak!.updateToken(30) as Promise<boolean>;
+ promise.then(tokenRefreshed => {
+ console.debug("Access token update success, refreshed from server: " + tokenRefreshed);
+ }).catch(() => {
+ console.error("Access token update failed.");
+ this._setAuthDisconnected(true);
+ });
+
+ // Using Promise.race() with a timeout of 15 seconds
+ // Since the timeout will never resolve, we assume only a boolean can be returned.
+ let timer: NodeJS.Timeout;
+ return Promise.race(
+ [promise, new Promise((_r, rej) => timer = setTimeout(rej, 15000))]
+ ).finally(() => clearTimeout(timer)) as Promise<boolean | void>;
}
protected async _getNativeOfflineRefreshToken(): Promise<string | undefined> {
@@ -1013,25 +1140,65 @@ export class Manager implements EventProviderFactory {
protected _setAuthenticated(authenticated: boolean) {
this._authenticated = authenticated;
- // Reconnect to websocket
if (this._events) {
this._events.disconnect();
}
-
if (!this._events) {
this.doEventsSubscriptionInit();
}
}
- protected _setDisconnected(disconnected: boolean) {
- if(this._disconnected !== disconnected) {
+ // When authentication service status changes; in most cases a failed token refresh.
+ // Always go OFFLINE if 'failed', only go back ONLINE when all EventProviders are also connected.
+ protected _setAuthDisconnected(disconnected: boolean, force = false) {
+ if(this._authDisconnected !== disconnected || force) {
+ console.debug(`Authentication service status changed: ${disconnected ? 'DISCONNECTED' : 'CONNECTED'}`);
+ if(disconnected) {
+ this._authDisconnected = true;
+ this._runAuthReconnectTimer();
+ this._emitEvent(OREvent.OFFLINE);
+ } else {
+ this._authDisconnected = false;
+ if(this._eventsDisconnected) {
+ this._tryReconnectEvents();
+ } else {
+ this._emitEvent(OREvent.ONLINE);
+ }
+ }
+ }
+ }
+
+ // When EventProvider (such as WebSocket) connection status changes.
+ // Always go OFFLINE if disconnected, only go back ONLINE when authentication is also connected.
+ protected _setEventDisconnected(disconnected: boolean, force = false) {
+ if(this._eventsDisconnected !== disconnected || force) {
+ console.debug(`EventProvider status changed: ${disconnected ? 'DISCONNECTED' : 'CONNECTED'}`);
if(disconnected) {
+ this._eventsDisconnected = true;
this._emitEvent(OREvent.OFFLINE);
+
+ // WebSocket might not connect because of token expiry, so we try updating it immediately.
+ // Since token expiry is unrelated to ONLINE/OFFLINE state, a successful token update would change _authDisconnected from FALSE to FALSE.
+ // So, if the token update is successful, we force update _authDisconnected.
+ if(this.isTokenExpired() && !this._authDisconnected) {
+ this._tryUpdateAccessToken().then((offline) => {
+ if(!offline) {
+ this._setAuthDisconnected(false, true);
+ }
+ });
+ }
+
} else {
- this._emitEvent(OREvent.ONLINE);
+ // When EventProvider is back online, check if authentication is disconnected and try to reauthenticate if necessary.
+ // Only emit the ONLINE event when both are connected.
+ this._eventsDisconnected = false;
+ if(this._authDisconnected) {
+ this._runAuthReconnectTimer()
+ } else {
+ this._emitEvent(OREvent.ONLINE);
+ }
}
}
- this._disconnected = disconnected;
}
}
diff --git a/ui/component/or-app/src/app.ts b/ui/component/or-app/src/app.ts
index 6162f3a3e..3bb23efd0 100644
--- a/ui/component/or-app/src/app.ts
+++ b/ui/component/or-app/src/app.ts
@@ -4,6 +4,7 @@ export interface AppState {
page: string;
params: {[k in string]: string} | null;
offline: boolean;
+ visible: boolean;
resolved: boolean,
drawerOpened: boolean;
scrollTop: number;
@@ -18,6 +19,7 @@ const INITIAL_STATE: AppState = {
page: "",
params: null,
offline: false,
+ visible: true,
resolved: false,
drawerOpened: false,
scrollTop: 0,
@@ -63,9 +65,15 @@ const appSlice = createSlice({
...state,
offline: action.payload
}
+ },
+ setVisibility(state, action: PayloadAction<boolean>) {
+ return {
+ ...state,
+ visible: action.payload
+ }
}
}
});
-export const {updatePage, updateDrawer, scrollToTop, updateRealm, setOffline} = appSlice.actions;
+export const {updatePage, updateDrawer, scrollToTop, updateRealm, setOffline, setVisibility} = appSlice.actions;
export const appReducer = appSlice.reducer;
diff --git a/ui/component/or-app/src/index.ts b/ui/component/or-app/src/index.ts
index 172250473..1523e26bf 100644
--- a/ui/component/or-app/src/index.ts
+++ b/ui/component/or-app/src/index.ts
@@ -11,9 +11,9 @@ import i18next from "i18next";
import manager, {BasicLoginResult, DefaultColor2, DefaultColor3, DefaultColor4, Manager, normaliseConfig, ORError, OREvent, Util} from "@openremote/core";
import {DEFAULT_LANGUAGES, HeaderConfig} from "./or-header";
import {OrMwcDialog, showDialog, showErrorDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
-import {OrMwcSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
+import {OrMwcSnackbar, showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
import {AnyAction, Store, Unsubscribe} from "@reduxjs/toolkit";
-import {AppStateKeyed, setOffline, updatePage, updateRealm} from "./app";
+import {AppStateKeyed, setOffline, setVisibility, updatePage, updateRealm} from "./app";
import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
import {Auth, ManagerConfig, Realm} from "@openremote/model";
import {pageOfflineProvider} from "./page-offline";
@@ -89,11 +89,16 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
@state()
protected _offline: boolean = false;
+ @state()
+ protected _showOfflineFallback: boolean = false;
+
@state()
protected _activeMenu?: string;
protected _onEventBind?: any;
+ protected _onVisibilityBind?: any;
protected _realms!: Realm[];
+ protected _offlineFallbackDeferred?: Util.Deferred<void>;
protected _store: Store<S, AnyAction>;
protected _storeUnsubscribe!: Unsubscribe;
@@ -163,14 +168,30 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
return this._store.getState();
}
+ // Using HTML 'visibilitychange' listener to see whether the Manager is visible for the user.
+ // TODO; Add an ConsoleProvider that listens to background/foreground changes, and dispatch the respective OREvent. This will improve responsiveness of logic attached to it.
+ // For example used for triggering reconnecting logic once the UI becomes visible again.
+ protected onVisibilityChange(ev: Event) {
+ if(document.visibilityState === "visible") {
+ this._onEvent(OREvent.CONSOLE_VISIBLE);
+ } else {
+ this._onEvent(OREvent.CONSOLE_HIDDEN);
+ }
+ }
+
connectedCallback() {
super.connectedCallback();
this._storeUnsubscribe = this._store.subscribe(() => this.stateChanged(this.getState()));
+ this._onVisibilityBind = this.onVisibilityChange.bind(this);
+ document.addEventListener("visibilitychange", this._onVisibilityBind);
this.stateChanged(this.getState());
}
disconnectedCallback() {
this._storeUnsubscribe();
+ if(this._onVisibilityBind) {
+ document.removeEventListener("visibilityChange", this._onVisibilityBind);
+ }
if(this._onEventBind) {
manager.removeListener(this._onEventBind);
}
@@ -293,11 +314,11 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
// If either page or 'offline'-status is changed, it should update to the correct page,
// by appending the page to the HTML content
- if (changedProps.has("_page") || changedProps.has("_offline")) {
+ if (changedProps.has("_page") || changedProps.has("_offline") || changedProps.has("_showOfflineFallback")) {
if (this._mainElem) {
const pageProvider = this.appConfig!.pages.find((page) => page.name === this._page);
- const showOfflineFallback = (this._offline && !pageProvider?.allowOffline);
+ const showOfflineFallback = (this._showOfflineFallback && !pageProvider?.allowOffline);
const offlinePage = this._mainElem.querySelector('#offline-page');
// If page has changed, replace the previous content with the new page.
@@ -318,21 +339,18 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
// CASE: "Offline overlay page is present, but should not be shown"
if(offlinePage && !showOfflineFallback) {
- console.log("Removing offline page fallback!");
- this._mainElem.removeChild(offlinePage);
- const elem = this._mainElem.firstElementChild as HTMLElement;
+ this._mainElem.removeChild(offlinePage); // remove offline overlay
- // If the current page is "loaded during offline", the content is either empty or invalid; so we recreate it.
- if(pageProvider && elem?.getAttribute('loadedDuringOffline') === 'true') {
- this._mainElem.replaceChild(pageProvider.pageCreator(), elem); // recreate page
- } else {
- elem?.style.removeProperty('display'); // show the current page again (back to the foreground)
+ const elem = this._mainElem.firstElementChild as Page<any>;
+ elem?.style.removeProperty('display'); // show the current page again (back to the foreground)
+ if(elem?.onRefresh) {
+ elem.onRefresh(); // If custom onRefresh() is set by the page, run that function.
}
}
// CASE: "Offline overlay page is NOT present, but needs to be there"
+ // It either shows the default offline fallback page, or a custom one defined in the AppConfig.
else if(!offlinePage && showOfflineFallback) {
- console.log("Showing offline page fallback!");
const newOfflinePage = (this.appConfig?.offlinePage) ? this.appConfig.offlinePage.pageCreator() : pageOfflineProvider(this._store).pageCreator();
(this._mainElem.firstElementChild as HTMLElement)?.style.setProperty('display', 'none'); // Hide the current page (to the background)
newOfflinePage.id = "offline-page";
@@ -419,9 +437,70 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
}
} else if(event === OREvent.ONLINE) {
if(this._offline) {
- this._store.dispatch((setOffline(false)))
+ this._showOfflineFallback = false;
+ this._completeOfflineFallbackTimer(); // complete fallback timer
+ this._store.dispatch((setOffline(false)));
}
+ } else if(event === OREvent.RECONNECT_FAILED) {
+ this._startOfflineFallbackTimer(); // start fallback timer (if not done yet)
+
+ } else if(event === OREvent.CONSOLE_VISIBLE) {
+ this._store.dispatch((setVisibility(true)));
+
+ // When the manager appears on Mobile devices, but the connection is OFFLINE,
+ // we reset the timer to the {appConfig.offlineTimeout} seconds. This is because we saw issues with reopening the app,
+ // and seeing a connection interval of 30+ seconds. We now give the user the benefit of the doubt, by resetting the timer.
+ if(manager.console?.isMobile && this._offline) {
+ this._startOfflineFallbackTimer(true);
+ }
+ // Always try reconnecting (if necessary)
+ manager.reconnect(true);
+
+ } else if(event === OREvent.CONSOLE_HIDDEN) {
+ this._store.dispatch((setVisibility(false)));
+ }
+ }
+
+ // Offline timer logic
+ //
+ // This will start a Deferred promise that keeps track of the 'wait before showing offline page' timer.
+ // - Resolving the promise updates the 'show offline fallback' variable based on OFFLINE state.
+ // - Rejecting the promise 'aborts the process' and skips that logic and does nothing.
+ //
+ // To explain; when the Manager reports "We're offline!" it will wait 10+ seconds before visually reporting the user that he/she is offline.
+ // However, if the user reconnects within that time period, we resolve this promise early. (which is why using Deferred is useful)
+ protected _startOfflineFallbackTimer(force = false): void {
+ if(force) {
+ this._completeOfflineFallbackTimer(true);
+ } else if(this._offlineFallbackDeferred || this._showOfflineFallback) {
+ return;
+ }
+
+ const deferred = new Util.Deferred<void>();
+ let finished = false;
+ deferred.promise.then(() => {
+ this._showOfflineFallback = this._offline;
+ }).finally(() => {
+ finished = true;
+ });
+
+ setTimeout(() => {
+ if(!finished) { deferred.resolve(); } // resolve THIS timer if not done yet.
+ }, this.appConfig?.offlineTimeout || 10000)
+
+ this._offlineFallbackDeferred = deferred;
+ }
+
+ // Completes and removes the 'show offline page' timer
+ // Resolving the timer updates the 'show offline fallback' variable based on OFFLINE state.
+ // if 'aborted' is TRUE it will skip that logic. See startOfflineTimer() for more details.
+ protected _completeOfflineFallbackTimer(aborted = false) {
+ if(aborted) {
+ this._offlineFallbackDeferred?.reject();
+ } else {
+ this._offlineFallbackDeferred?.resolve();
}
+ this._offlineFallbackDeferred = undefined;
}
public logout() {
diff --git a/ui/component/or-app/src/page-offline.ts b/ui/component/or-app/src/page-offline.ts
index fdb988df4..ee0e52f44 100644
--- a/ui/component/or-app/src/page-offline.ts
+++ b/ui/component/or-app/src/page-offline.ts
@@ -18,6 +18,7 @@ const styling = css`
width: 100%;
flex-direction: column;
gap: 32px;
+ padding: 0 32px;
}
#offline-icon {
@@ -35,6 +36,20 @@ const styling = css`
font-size: 24px;
font-weight: bold;
}
+
+ #reconnecting-text:after {
+ display: inline-block;
+ animation: dotty steps(2,end) 2s infinite;
+ content: '';
+ }
+
+ @keyframes dotty {
+ 0% { content: ''; }
+ 25% { content: '.'; }
+ 50% { content: '..'; }
+ 75% { content: '...'; }
+ 100% { content: ''; }
+ }
`
async function* countDown(count: number) {
@@ -60,11 +75,6 @@ export function pageOfflineProvider(store: Store<AppStateKeyed>): PageProvider<A
@customElement("page-offline")
export class PageOffline extends Page<AppStateKeyed> {
- @state()
- protected _timer?: AsyncGenerator<number | undefined>;
-
- protected _onEventBind?: any;
-
static get styles() {
return [styling]
}
@@ -72,55 +82,17 @@ export class PageOffline extends Page<AppStateKeyed> {
public stateChanged(state: AppStateKeyed) {
}
- connectedCallback() {
- super.connectedCallback();
- this._onEventBind = this._onEvent.bind(this);
- manager.addListener(this._onEventBind);
- }
-
- disconnectedCallback() {
- super.disconnectedCallback();
- if(this._onEventBind) {
- manager.removeListener(this._onEventBind);
- }
- }
-
- protected _onEvent(event: OREvent) {
- if (event === OREvent.CONNECTING) {
- this._startTimer(10);
- }
- }
-
- protected _startTimer(seconds: number) {
- const timer = countDown(seconds);
- this._timer = timer;
- setTimeout(() => {
- this._stopTimer(timer); // stop after the amount of seconds is passed.
- }, seconds * 1000)
- }
-
- // Stopping the timer/timeout if it is the current active timer
- protected _stopTimer(timer: AsyncGenerator<number | undefined>) {
- if(this._timer === timer) {
- delete this._timer;
- }
- }
-
protected render(): TemplateResult {
return html`
<div id="offline-wrapper">
<or-icon id="offline-icon" icon="web-off"></or-icon>
<div id="offline-text-container">
- <span id="offline-title"">${i18next.t('youAreOffline')}</span>
- <span>${i18next.t('checkConnection')}</span>
+ <span id="offline-title""><or-translate value="youAreOffline"></or-translate></span>
+ <span id="offline-subtitle"><or-translate value="checkConnection"></or-translate></span>
+ </div>
+ <div>
+ <span><or-translate id="reconnecting-text" value="reconnecting"></or-translate></span>
</div>
- <!-- Countdown to when it tries reconnecting again -->
- ${when(this._timer, () => {
- const splitMsg = i18next.t("retryingConnection").split('{{seconds}}');
- return html`${splitMsg[0]} ${asyncReplace(this._timer!)} ${splitMsg[1]}`;
- }, () => html`
- ${i18next.t('reconnecting')}...
- `)}
</div>
`
}
diff --git a/ui/component/or-app/src/types.ts b/ui/component/or-app/src/types.ts
index a4b685f1f..dcc2bb16e 100644
--- a/ui/component/or-app/src/types.ts
+++ b/ui/component/or-app/src/types.ts
@@ -22,6 +22,7 @@ export interface RealmAppConfig {
export interface AppConfig<S extends AppStateKeyed> {
pages: PageProvider<S>[];
offlinePage?: PageProvider<S>; // override for fallback page when user is offline/disconnected
+ offlineTimeout?: number;
languages?: Languages;
superUserHeader?: HeaderConfig;
realms?: {
@@ -46,6 +47,10 @@ export abstract class Page<S extends AppStateKeyed> extends translate(i18next)(L
protected _storeUnsubscribe!: Unsubscribe;
+ // onRefresh() gets called by or-app to (as silent as possible) refresh the content of the page.
+ // If undefined (default), it will fully rerender the Web Component.
+ onRefresh?: () => void;
+
constructor(store: Store<S, AnyAction>) {
super();
this._store = store;