Skip to content

armgit / core

Public Imported from GitHub
0

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

Added offline fallback page, with configurable override per app (#1090)

Martin Peeters2a83dbf08dc1
diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.json
index 3f7491488..d614eeb3b 100644
--- a/manager/src/web/shared/locales/en/or.json
+++ b/manager/src/web/shared/locales/en/or.json
@@ -322,6 +322,10 @@
"host": "Hostname",
"errorOccurred": "An error has occurred",
"sendFailed": "Send failed",
+ "youAreOffline": "You are offline",
+ "checkConnection": "Please check your connection",
+ "retryingConnection": "Retrying in {{seconds}} seconds",
+ "reconnecting": "Reconnecting",
"managerError": {
"MANAGER_FAILED_TO_LOAD": "Manager failed to load (see console logs)",
"AUTH_FAILED": "Auth failed to load (see console logs)",
diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.json
index 24f5f8919..b8fb14630 100644
--- a/manager/src/web/shared/locales/nl/or.json
+++ b/manager/src/web/shared/locales/nl/or.json
@@ -322,6 +322,10 @@
"host": "Hostname",
"errorOccurred": "Er is een fout opgetreden",
"sendFailed": "Verzenden mislukt",
+ "youAreOffline": "Geen internet",
+ "checkConnection": "Controleer je internetverbinding",
+ "retryingConnection": "Opnieuw proberen na {{seconds}} seconden",
+ "reconnecting": "Verbinden",
"managerError": {
"MANAGER_FAILED_TO_LOAD": "Manager kan niet geladen worden (bekijk de console logs)",
"AUTH_FAILED": "Auth kan niet geladen worden (bekijk de console logs)",
diff --git a/ui/component/core/src/index.ts b/ui/component/core/src/index.ts
index 1f60a3af6..d7aced87e 100644
--- a/ui/component/core/src/index.ts
+++ b/ui/component/core/src/index.ts
@@ -46,7 +46,8 @@ export declare type Keycloak = {
login(options?: any): void;
hasRealmRole(role: string): boolean;
logout(options?: any): void;
- updateToken(expiry: number): PromiseLike<boolean>;
+ isTokenExpired(expiry?: number): boolean;
+ updateToken(expiry?: number): PromiseLike<boolean>;
clearToken(): void;
}
@@ -62,11 +63,11 @@ export enum ORError {
export enum OREvent {
ERROR = "ERROR",
READY = "READY",
+ ONLINE = "ONLINE",
+ OFFLINE = "OFFLINE",
+ CONNECTING = "CONNECTING",
CONSOLE_INIT = "CONSOLE_INIT",
CONSOLE_READY = "CONSOLE_READY",
- EVENTS_CONNECTED = "EVENTS_CONNECTED",
- EVENTS_CONNECTING = "EVENTS_CONNECTING",
- EVENTS_DISCONNECTED = "EVENTS_DISCONNECTED",
TRANSLATE_INIT = "TRANSLATE_INIT",
TRANSLATE_LANGUAGE_CHANGED = "TRANSLATE_LANGUAGE_CHANGED",
DISPLAY_REALM_CHANGED = "DISPLAY_REALM_CHANGED"
@@ -274,6 +275,8 @@ export class Manager implements EventProviderFactory {
private _error?: ORError;
private _config!: ManagerConfig;
private _authenticated: boolean = false;
+ private _disconnected: boolean = false;
+ private _reconnectInterval?: number;
private _ready: boolean = false;
private _readyCallback?: () => PromiseLike<any>;
private _name: string = "";
@@ -586,16 +589,57 @@ 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) => {
+ if(!disconnected) {
+ clearInterval(this._reconnectInterval);
+ delete this._reconnectInterval;
+ }
+ });
+ }, timeout);
+ }
+ }
+
+ protected async _attemptReconnect(): Promise<boolean> {
+
+ this._setDisconnected(true);
+ this._emitEvent(OREvent.CONNECTING); // emit event every time a reconnect attempt is made
+
+ // 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;
+ }
+
protected _onEventProviderStatusChanged(status: EventProviderStatus) {
switch (status) {
case EventProviderStatus.DISCONNECTED:
- this._emitEvent(OREvent.EVENTS_DISCONNECTED);
+ console.log("Event provider disconnected.");
+ this._emitEvent(OREvent.OFFLINE);
break;
case EventProviderStatus.CONNECTED:
- this._emitEvent(OREvent.EVENTS_CONNECTED);
+ console.log("Event provider connected.")
+ this._emitEvent(OREvent.ONLINE);
break;
case EventProviderStatus.CONNECTING:
- this._emitEvent(OREvent.EVENTS_CONNECTING);
+ this._emitEvent(OREvent.CONNECTING);
break;
}
}
@@ -883,19 +927,10 @@ export class Manager implements EventProviderFactory {
};
this._keycloak!.onAuthRefreshError = () => {
- // Refresh token expired (either SSO max session duration or offline idle timeout), see
- // OR_IDENTITY_SESSION_MAX_MINUTES and OR_IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES server config
- fetch(this._config.keycloakUrl! + "/health/ready", {method: 'HEAD', mode: 'no-cors'})
- .then((response) => {
- if(response.status === 200) {
- this._keycloak!.clearToken();
- this._keycloak!.login();
- } else {
- console.error("Something went wrong reaching the keycloak server. Not redirecting.")
- }
- }).catch(() => {
- console.error("Could not reach keycloak server. Not redirecting.")
- })
+ console.log("Failed to refresh the access token.")
+ if(this._keycloak?.isTokenExpired()) {
+ this._runReconnectTimer();
+ }
}
try {
@@ -922,7 +957,10 @@ export class Manager implements EventProviderFactory {
delete this._keycloakUpdateTokenInterval;
}
this._keycloakUpdateTokenInterval = window.setInterval(() => {
- this.updateKeycloakAccessToken();
+ // only try to update token when online, otherwise the reconnect logic (this._attemptReconnect()) will try this
+ if(!this._disconnected) {
+ this.updateKeycloakAccessToken();
+ }
}, 10000);
this._onAuthenticated();
}
@@ -983,6 +1021,17 @@ export class Manager implements EventProviderFactory {
this.doEventsSubscriptionInit();
}
}
+
+ protected _setDisconnected(disconnected: boolean) {
+ if(this._disconnected !== disconnected) {
+ if(disconnected) {
+ this._emitEvent(OREvent.OFFLINE);
+ } else {
+ this._emitEvent(OREvent.ONLINE);
+ }
+ }
+ this._disconnected = disconnected;
+ }
}
export const manager = new Manager(); // Needed for webpack bundling
diff --git a/ui/component/or-app/src/app.ts b/ui/component/or-app/src/app.ts
index d6caa9d57..6162f3a3e 100644
--- a/ui/component/or-app/src/app.ts
+++ b/ui/component/or-app/src/app.ts
@@ -57,9 +57,15 @@ const appSlice = createSlice({
...state,
realm: action.payload
}
+ },
+ setOffline(state, action: PayloadAction<boolean>) {
+ return {
+ ...state,
+ offline: action.payload
+ }
}
}
});
-export const {updatePage, updateDrawer, scrollToTop, updateRealm} = appSlice.actions;
+export const {updatePage, updateDrawer, scrollToTop, updateRealm, setOffline} = 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 de21b823a..3c6815b6b 100644
--- a/ui/component/or-app/src/index.ts
+++ b/ui/component/or-app/src/index.ts
@@ -1,11 +1,4 @@
-import {
- css,
- html,
- LitElement,
- PropertyValues,
- TemplateResult,
- unsafeCSS
-} from "lit";
+import {css, html, LitElement, PropertyValues, TemplateResult, unsafeCSS} from "lit";
import {customElement, property, query, state} from "lit/decorators.js";
import {AppConfig, Page, RealmAppConfig, router} from "./types";
import "@openremote/or-translate";
@@ -15,15 +8,15 @@ import "./or-header";
import "@openremote/or-icon";
import {updateMetadata} from "pwa-helpers/metadata";
import i18next from "i18next";
-import manager, {DefaultColor2, DefaultColor3, DefaultColor4, Util, BasicLoginResult, normaliseConfig, Manager} from "@openremote/core";
+import manager, {BasicLoginResult, DefaultColor2, DefaultColor3, DefaultColor4, Manager, normaliseConfig, ORError, OREvent, Util} from "@openremote/core";
import {DEFAULT_LANGUAGES, HeaderConfig} from "./or-header";
-import {OrMwcDialog, showErrorDialog, showDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
+import {OrMwcDialog, showDialog, showErrorDialog} from "@openremote/or-mwc-components/or-mwc-dialog";
import {OrMwcSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";
import {AnyAction, Store, Unsubscribe} from "@reduxjs/toolkit";
-import {AppStateKeyed, updatePage, updateRealm} from "./app";
-import { InputType, OrInputChangedEvent } from "@openremote/or-mwc-components/or-mwc-input";
-import { ORError } from "@openremote/core";
-import { Auth, ManagerConfig, Realm } from "@openremote/model";
+import {AppStateKeyed, setOffline, 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";
export const DefaultLogo = require("../images/logo.svg");
export const DefaultMobileLogo = require("../images/logo-mobile.svg");
@@ -93,9 +86,13 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
@state()
protected _realm?: string;
+ @state()
+ protected _offline: boolean = false;
+
@state()
protected _activeMenu?: string;
+ protected _onEventBind?: any;
protected _realms!: Realm[];
protected _store: Store<S, AnyAction>;
protected _storeUnsubscribe!: Unsubscribe;
@@ -170,6 +167,9 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
disconnectedCallback() {
this._storeUnsubscribe();
+ if(this._onEventBind) {
+ manager.removeListener(this._onEventBind);
+ }
super.disconnectedCallback();
}
@@ -241,6 +241,10 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
this._initialised = true;
+ // Register listener to change global state based on certain events
+ this._onEventBind = this._onEvent.bind(this);
+ manager.addListener(this._onEventBind);
+
// Create route listener to set header active item (this must be done before any routes added)
const headerUpdater = (activeMenu: string | undefined) => {
this._activeMenu = activeMenu;
@@ -283,18 +287,50 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
return;
}
- if (changedProps.has("_page")) {
+ // 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 (this._mainElem) {
- if (this._mainElem.firstElementChild) {
- this._mainElem.firstElementChild.remove();
+
+ const pageProvider = this.appConfig!.pages.find((page) => page.name === this._page);
+ const showOfflineFallback = (this._offline && !pageProvider?.allowOffline);
+ const offlinePage = this._mainElem.querySelector('page-offline');
+
+ // If page has changed, replace the previous content with the new page.
+ // However, if no page is present yet, append it to the page.
+ if(changedProps.has('_page') && pageProvider) {
+ const currentPage = this._mainElem.firstElementChild;
+ if(currentPage) {
+ const newPage = pageProvider.pageCreator();
+ if(showOfflineFallback) {
+ newPage.style.setProperty('display', 'none'); // hide the new page while offline overlay page is shown
+ newPage.setAttribute('loadedDuringOffline', 'true'); // mark the page as "loaded during offline", since the content is either empty or invalid
+ }
+ this._mainElem.replaceChild(newPage, currentPage); // replace content
+ } else {
+ this._mainElem.appendChild(pageProvider.pageCreator());
+ }
}
- if (this._page) {
- const pageProvider = this.appConfig!.pages.find((page) => page.name === this._page);
- if (pageProvider) {
- const pageElem = pageProvider.pageCreator();
- this._mainElem.appendChild(pageElem);
+
+ // CASE: "Offline overlay page is present, but should not be shown"
+ if(offlinePage && !showOfflineFallback) {
+ this._mainElem.removeChild(offlinePage);
+ const elem = this._mainElem.firstElementChild as HTMLElement;
+
+ // 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)
}
}
+
+ // CASE: "Offline overlay page is NOT present, but needs to be there"
+ else if(!offlinePage && showOfflineFallback) {
+ 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)
+ this._mainElem.appendChild(newOfflinePage);
+ }
}
this.updateWindowTitle();
@@ -366,6 +402,20 @@ export class OrApp<S extends AppStateKeyed> extends LitElement {
public stateChanged(state: AppStateKeyed) {
this._realm = state.app.realm;
this._page = state.app!.page;
+ this._offline = state.app!.offline;
+ }
+
+ protected _onEvent(event: OREvent) {
+ if(event === OREvent.OFFLINE) {
+ if(!this._offline) {
+ this._store.dispatch((setOffline(true)))
+ }
+ }
+ if(event === OREvent.ONLINE) {
+ if(this._offline) {
+ this._store.dispatch((setOffline(false)))
+ }
+ }
}
public logout() {
diff --git a/ui/component/or-app/src/page-offline.ts b/ui/component/or-app/src/page-offline.ts
new file mode 100644
index 000000000..fdb988df4
--- /dev/null
+++ b/ui/component/or-app/src/page-offline.ts
@@ -0,0 +1,131 @@
+import {Page, PageProvider} from "./types";
+import {css, html, TemplateResult} from "lit";
+import {customElement, state} from "lit/decorators.js";
+import {AppStateKeyed} from "./app";
+import {Store} from "@reduxjs/toolkit";
+import {i18next} from "@openremote/or-translate";
+import manager, {OREvent} from "@openremote/core";
+import {asyncReplace} from 'lit/directives/async-replace.js';
+import {when} from 'lit/directives/when.js';
+
+// language=css
+const styling = css`
+ #offline-wrapper {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 100%;
+ width: 100%;
+ flex-direction: column;
+ gap: 32px;
+ }
+
+ #offline-icon {
+ font-size: 64px;
+ }
+
+ #offline-text-container {
+ display: flex;
+ align-items: center;
+ flex-direction: column;
+ gap: 16px;
+ }
+
+ #offline-title {
+ font-size: 24px;
+ font-weight: bold;
+ }
+`
+
+async function* countDown(count: number) {
+ while (count > 0) {
+ yield count--;
+ await new Promise((r) => setTimeout(r, 1000));
+ }
+}
+
+export function pageOfflineProvider(store: Store<AppStateKeyed>): PageProvider<AppStateKeyed> {
+ return {
+ name: "offline",
+ routes: [
+ "offline"
+ ],
+ pageCreator: () => {
+ return new PageOffline(store);
+ }
+ };
+}
+
+
+@customElement("page-offline")
+export class PageOffline extends Page<AppStateKeyed> {
+
+ @state()
+ protected _timer?: AsyncGenerator<number | undefined>;
+
+ protected _onEventBind?: any;
+
+ static get styles() {
+ return [styling]
+ }
+
+ 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>
+ </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>
+ `
+ }
+
+ get name(): string {
+ return "offline";
+ }
+}
diff --git a/ui/component/or-app/src/types.ts b/ui/component/or-app/src/types.ts
index 67eaa4abc..a4b685f1f 100644
--- a/ui/component/or-app/src/types.ts
+++ b/ui/component/or-app/src/types.ts
@@ -21,6 +21,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
languages?: Languages;
superUserHeader?: HeaderConfig;
realms?: {
@@ -33,6 +34,7 @@ export interface AppConfig<S extends AppStateKeyed> {
export interface PageProvider<S extends AppStateKeyed> {
name: string;
routes: string[];
+ allowOffline?: boolean; // allow use during offline/disconnected state. Default is false.
pageCreator: () => Page<S>;
}
diff --git a/ui/demo/demo-or-thermostat/src/index.ts b/ui/demo/demo-or-thermostat/src/index.ts
index e37435236..4b7fa8bd6 100644
--- a/ui/demo/demo-or-thermostat/src/index.ts
+++ b/ui/demo/demo-or-thermostat/src/index.ts
@@ -51,7 +51,7 @@ async function refreshUI(assetId:string) {
manager.addListener((event: OREvent) => {
console.log("OR Event:" + event);
- if(event === OREvent.EVENTS_CONNECTED) {
+ if(event === OREvent.ONLINE) {
initApartment1Asset().then(assetId => {
if (assetId) {
refreshUI(assetId);