100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Console related updates
Rich Turner7ddf1a6ba6c9
diff --git a/model/src/main/java/org/openremote/model/console/ConsoleProvider.java b/model/src/main/java/org/openremote/model/console/ConsoleProvider.javaindex e7687a655..eb804bf58 100644--- a/model/src/main/java/org/openremote/model/console/ConsoleProvider.java+++ b/model/src/main/java/org/openremote/model/console/ConsoleProvider.java@@ -33,6 +33,7 @@ public class ConsoleProvider {protected boolean requiresPermission;protected boolean hasPermission;protected boolean success;+ protected boolean enabled;protected boolean disabled;protected ObjectValue data;@@ -41,6 +42,7 @@ public class ConsoleProvider {@JsonProperty("requiresPermission") boolean requiresPermission,@JsonProperty("hasPermission") boolean hasPermission,@JsonProperty("success") boolean success,+ @JsonProperty("enabled") boolean enabled,@JsonProperty("disabled") boolean disabled,@JsonProperty("data") ObjectValue data) {this.version = version;@@ -48,6 +50,7 @@ public class ConsoleProvider {this.hasPermission = hasPermission;this.success = success;this.disabled = disabled;+ this.enabled = enabled;this.data = data;}@@ -67,6 +70,10 @@ public class ConsoleProvider {return success;}+ public boolean isEnabled() {+ return enabled;+ }+public boolean isDisabled() {return disabled;}@@ -84,11 +91,12 @@ public class ConsoleProvider {}boolean hasPermission = obj.getBoolean("hasPermission").orElse(!requiresPermission.get());+ boolean enabled = obj.getBoolean("enabled").orElse(false);boolean disabled = obj.getBoolean("disabled").orElse(false);boolean success = obj.getBoolean("success").orElse(false);ObjectValue data = obj.getObject("data").orElse(null);- return Optional.of(new ConsoleProvider(version.get(), requiresPermission.get(), hasPermission, success, disabled, data));+ return Optional.of(new ConsoleProvider(version.get(), requiresPermission.get(), hasPermission, success, enabled, disabled, data));});}@@ -97,6 +105,7 @@ public class ConsoleProvider {obj.put("version", getVersion());obj.put("requiresPermission", isRequiresPermission());obj.put("hasPermission", isHasPermission());+ obj.put("enabled", isEnabled());obj.put("disabled", isDisabled());if (data != null) {obj.put("data", getData());diff --git a/model/src/main/java/org/openremote/model/console/ConsoleRegistration.java b/model/src/main/java/org/openremote/model/console/ConsoleRegistration.javaindex 2f11fb261..69284ac24 100644--- a/model/src/main/java/org/openremote/model/console/ConsoleRegistration.java+++ b/model/src/main/java/org/openremote/model/console/ConsoleRegistration.java@@ -48,10 +48,10 @@ import java.util.Map;* "requiresPermission": true* }* },- * "apps": {- * "manager": "1.0.0",- * "customerA": "1.0.0"- * }+ * "apps": [+ * "manager"+ * "customerA"+ * ]* }</pre></blockquote>* <p>* An Android console app called "Smart City" on a Samsung Galaxy S9 running Android 8.0 would generate the following@@ -79,9 +79,9 @@ import java.util.Map;* "requiresPermission": true* }* },- * "apps": {- * "smartcity": "1.0.0"- * }+ * "apps": [+ * "smartcity"+ * ]* }</pre></blockquote>*/public class ConsoleRegistration {@@ -91,7 +91,7 @@ public class ConsoleRegistration {protected String platform;protected String model;protected Map<String, ConsoleProvider> providers;- protected Map<String, String> apps;+ protected String[] apps;@JsonCreatorpublic ConsoleRegistration(@JsonProperty("id") String id,@@ -100,7 +100,7 @@ public class ConsoleRegistration {@JsonProperty("platform") String platform,@JsonProperty("providers") Map<String, ConsoleProvider> providers,@JsonProperty("model") String model,- @JsonProperty("apps") Map<String, String> apps) {+ @JsonProperty("apps") String[] apps) {this.id = id;this.name = name;this.version = version;@@ -138,7 +138,7 @@ public class ConsoleRegistration {return providers;}- public Map<String, String> getApps() {+ public String[] getApps() {return apps;}}diff --git a/ui/component/core/src/console.ts b/ui/component/core/src/console.tsindex 14d6b856b..df0feabe0 100644--- a/ui/component/core/src/console.ts+++ b/ui/component/core/src/console.ts@@ -1,5 +1,7 @@import {ConsoleRegistration} from "@openremote/model";import rest from "@openremote/rest";+import openremote from "./index";+import {AxiosResponse} from "axios";declare function require(name: string): any;@@ -10,6 +12,8 @@ export interface ProviderMessage {provider: string;action: string;data?: any;++ [x: string]: any;}interface ProviderInitialiseResponse extends ProviderMessage {@@ -17,6 +21,7 @@ interface ProviderInitialiseResponse extends ProviderMessage {requiresPermission: boolean;hasPermission: boolean;success: boolean;+ enabled: boolean;}export interface ProviderEnableRequest extends ProviderMessage {@@ -31,13 +36,14 @@ export interface ProviderEnableResponse extends ProviderMessage {export class Console {protected _realm: string;- private _registration: ConsoleRegistration;- private _autoEnable: boolean = false;+ protected _registration: ConsoleRegistration;+ protected _autoEnable: boolean = false;protected _initialised: boolean = false;protected _initialiseInProgress: boolean = false;protected _pendingProviderPromises: { [name: string]: ((response: any) => void) | null } = {};- private _pendingProviderEnables: string[] = [];+ protected _pendingProviderEnables: string[] = [];protected _enableCompleteCallback: (() => void) | null;+ protected _registrationTimer: number | null = null;constructor(realm: string, autoEnable: boolean, enableComplete: () => void) {@@ -57,11 +63,7 @@ export class Console {let consoleProviders = queryParams.get("consoleProviders");let autoEnableStr = queryParams.get("consoleAutoEnable");- if (!consoleProviders) {- //consoleProviders = "push"; // Use push provider by default- }-- let requestedProviders = consoleProviders && consoleProviders.length > 0 ? consoleProviders.split(" ") : [];+ let requestedProviders = consoleProviders && consoleProviders.length > 0 ? consoleProviders.split(" ") : ["push", "storage"];this._pendingProviderEnables = consoleProviders && consoleProviders.length > 0 ? consoleProviders.split(" ") : [];// Look for existing console registration in local storage or just create a new one@@ -70,7 +72,20 @@ export class Console {let consoleRegStr = window.localStorage.getItem("OpenRemoteConsole:" + realm);if (consoleRegStr) {try {- consoleReg = JSON.parse(consoleRegStr) as ConsoleRegistration;+ let storedRegObj = JSON.parse(consoleRegStr);+ let storedReg = storedRegObj as ConsoleRegistration;+ if (storedReg.id) {+ consoleReg.id = storedReg.id;+ }+ if (storedReg.name) {+ consoleReg.name = storedReg.name;+ }+ if (storedReg.providers) {+ consoleReg.providers = storedReg.providers;+ }+ if (storedReg.apps) {+ consoleReg.apps = storedReg.apps;+ }} catch (e) {console.error("Failed to deserialise console registration");}@@ -80,14 +95,22 @@ export class Console {consoleReg.providers = {};for (let providerName of requestedProviders) {- let provider = oldProviders && oldProviders.hasOwnProperty(providerName) ? oldProviders[providerName] : {disabled: false};+ let provider = oldProviders && oldProviders.hasOwnProperty(providerName) ? oldProviders[providerName] : {+ enabled: false,+ disabled: false+ };consoleReg.providers[providerName] = provider;- if (provider.disabled) {+ if (provider.disabled || provider.enabled) {let index = this._pendingProviderEnables.indexOf(providerName);this._pendingProviderEnables.splice(index, 1);}}+ let appName = openremote.getAppName();+ if (appName.length > 0 && consoleReg.apps!.indexOf(appName) < 0) {+ consoleReg.apps!.push(appName);+ }+this._registration = consoleReg;if (consoleName) {@@ -148,21 +171,7 @@ export class Console {if (this._registration.providers) {for (let providerName of Object.keys(this._registration.providers)) {- let initResponse = await this._initialiseProvider(providerName);-- this._registration.providers![providerName].version = initResponse.version;- this._registration.providers![providerName].requiresPermission = initResponse.requiresPermission;- this._registration.providers![providerName].hasPermission = initResponse.hasPermission;- this._registration.providers![providerName].success = initResponse.success;-- if (!initResponse.success) {- console.debug("Provider initialisation failed: '" + providerName + "'");- this._registration.providers![providerName].disabled = true;- let index = this._pendingProviderEnables.indexOf(providerName);- if (index >= 0) {- this._pendingProviderEnables.splice(index, 1);- }- }+ await this._initialiseProvider(providerName);}}@@ -170,13 +179,10 @@ export class Console {this._initialiseInProgress = false;if (this._pendingProviderEnables.length === 0) {- let callback = this._enableCompleteCallback;- this._enableCompleteCallback = null;- if (callback) {- window.setTimeout(() => {- callback!()- }, 0);- }+ this.sendRegistration();+ this._callCompletedCallback();+ } else if (this._autoEnable) {+ await this.enableProviders();}} catch (e) {console.error(e);@@ -184,24 +190,6 @@ export class Console {}}- protected static _createConsoleRegistration(): ConsoleRegistration {- let reg: ConsoleRegistration = {- name: platform.name,- version: platform.version,- platform: platform.os.toString(),- model: ((platform.manufacturer ? platform.manufacturer + " " : "") + (platform.product ? platform.product : "")).trim()- };-- return reg;- }-- protected async _initialiseProvider(provider: string): Promise<ProviderInitialiseResponse> {- console.debug("Console: initialising provider '" + provider + "'");- return await this.sendProviderMessage({- provider: provider,- action: "PROVIDER_INIT"- }, true);- }// This mechanism doesn't support sending extra data to the providers being enabled and it doesn't allow data// to be retrieved from the replies; if that is required then providers should be manually enabled from the calling app@@ -215,35 +203,37 @@ export class Console {}}- public async enableProvider(provider: string, data?: any): Promise<ProviderEnableResponse> {+ public async enableProvider(providerName: string, data?: any): Promise<ProviderEnableResponse> {if (!this._initialised) {console.debug("Console must be initialised before disabling providers");throw new Error("Console must be initialised before enabling providers");}- if (!this._registration.providers!.hasOwnProperty(provider)) {- console.debug("Invalid console provider '" + provider + "'");- throw new Error("Invalid console provider '" + provider + "'");+ if (!this._registration.providers!.hasOwnProperty(providerName)) {+ console.debug("Invalid console provider '" + providerName + "'");+ throw new Error("Invalid console provider '" + providerName + "'");}- console.debug("Console: enabling provider '" + provider + "'");+ console.debug("Console: enabling provider '" + providerName + "'");let msg: ProviderEnableRequest = {- provider: provider,+ provider: providerName,action: "PROVIDER_ENABLE",consoleId: this._registration.id!,data};let response = await this.sendProviderMessage(msg, true);- let index = this._pendingProviderEnables.indexOf(provider);++ this._registration.providers![providerName].hasPermission = response.hasPermission;+ this._registration.providers![providerName].success = response.success;+ this._registration.providers![providerName].enabled = response.success;++ let index = this._pendingProviderEnables.indexOf(providerName);if (index >= 0) {this._pendingProviderEnables.splice(index, 1);if (this._pendingProviderEnables.length === 0) {- let callback = this._enableCompleteCallback;- this._enableCompleteCallback = null;- if (callback) {- callback();- }+ this.sendRegistration();+ this._callCompletedCallback();}}@@ -268,10 +258,11 @@ export class Console {action: "PROVIDER_DISABLE"}, true);this._registration.providers![provider].disabled = true;+ this._registration.providers![provider].enabled = false;return response;}- public async sendProviderMessage(message: ProviderMessage, waitForResponse: boolean) : Promise<any> {+ public async sendProviderMessage(message: ProviderMessage, waitForResponse: boolean): Promise<any | null> {if (!this._registration.providers!.hasOwnProperty(message.provider)) {console.debug("Invalid console provider '" + message.provider + "'");throw new Error("Invalid console provider '" + message.provider + "'");@@ -288,34 +279,62 @@ export class Console {throw new Error("Message already pending for provider '" + name + "' with action '" + message.action + "'");}- await new Promise(resolve => {+ return await new Promise(resolve => {this._pendingProviderPromises[promiseName] = resolve;this._doSendProviderMessage(message);});}- private _doSendProviderMessage(msg: any) {- if (this.isMobile) {- this.postNativeShellMessage({type: "provider", data: msg});- } else {- // TODO: Implement web browser provider handling (web push etc.)+ // Uses a delayed mechanism to avoid excessive calls to the server during enabling providers+ public async sendRegistration(): Promise<void> {+ if (this._registrationTimer) {+ window.clearTimeout(this._registrationTimer);+ this._registrationTimer = null;}++ await new Promise(resolve => {+ this._registrationTimer = window.setTimeout(() => {+ this._registrationTimer = null;+ console.debug("Console: updating registration");++ try {+ rest.api.ConsoleResource.register(this._registration).then((response: AxiosResponse<ConsoleRegistration>) => {+ if (response.status !== 200) {+ throw new Error("Failed to register console");+ }++ this._registration = response.data;+ console.debug("Console: registration successful");+ console.debug("Console: updating locally stored registration");+ window.localStorage.setItem("OpenRemoteConsole:" + this._realm, JSON.stringify(this._registration));+ });+ } finally {+ resolve();+ }+ }, 2000);+ });+ }++ public storeData(key: string, value: string | null) {+ this.sendProviderMessage({+ provider: "storage",+ action: "STORE",+ key: key,+ value: value+ }, false);}- public async sendRegistration(): Promise<void> {- console.debug("Console: updating registration");- let response = await rest.api.ConsoleResource.register(this._registration);- if (response.status !== 200) {- throw new Error("Failed to register console");- }- this._registration = response.data;- console.debug("Console: registration successful");- console.debug("Console: updating locally stored registration");- window.localStorage.setItem("OpenRemoteConsole:" + this._realm, JSON.stringify(this._registration));+ public async retrieveData(key: string): Promise<string | null> {+ let response = await this.sendProviderMessage({+ provider: "storage",+ action: "RETRIEVE",+ key: key+ }, true) as string;+ return response;}- public postNativeShellMessage(jsonMessage: any) {+ protected _postNativeShellMessage(jsonMessage: any) {if (this.shellAndroid) {// @ts-ignorereturn window.MobileInterface.postMessage(JSON.stringify(jsonMessage));@@ -326,19 +345,8 @@ export class Console {}}- protected readNativeShellMessage(messageKey: string): string | null {- if (this.shellAndroid) {- // @ts-ignore- return window.MobileInterface.getMessage(messageKey);- }- if (this.shellApple) {- return prompt(messageKey);- }- return null;- }-// This is called by native web view code- handleProviderResponse(msg: any) {+ protected _handleProviderResponse(msg: any) {if (!msg) {return;}@@ -347,11 +355,157 @@ export class Console {let name = msgJson.provider;let action = msgJson.action;- let resolve = this._pendingProviderPromises[name+action];+ let resolve = this._pendingProviderPromises[name + action];if (resolve != null) {- this._pendingProviderPromises[name+action] = null;+ this._pendingProviderPromises[name + action] = null;resolve(msgJson);}}++ protected _doSendProviderMessage(msg: any) {+ if (this.isMobile) {+ this._postNativeShellMessage({type: "provider", data: msg});+ } else {+ if (!msg.provider || !msg.action) {+ return;+ }+ switch (msg.provider.trim().toUpperCase()) {+ // TODO: Implement web browser provider handling (web push etc.)+ case "PUSH":++ switch (msg.action.trim().toUpperCase()) {+ case "PROVIDER_INIT":+ this._handleProviderResponse(JSON.stringify({+ action: "PROVIDER_INIT",+ provider: "push",+ version: "web",+ enabled: true,+ requiresPermission: false+ }));+ break;+ case "PROVIDER_ENABLE":+ this._handleProviderResponse(JSON.stringify({+ action: "PROVIDER_ENABLE",+ provider: "push",+ hasPermission: true,+ success: true+ }));+ break;+ default:+ throw new Error("Unsupported provider '" + msg.provider + "' and action '" + msg.action + "'");+ }++ break;++ case "STORAGE":++ switch (msg.action) {+ case "PROVIDER_INIT":+ this._handleProviderResponse(JSON.stringify({+ action: "PROVIDER_INIT",+ provider: "storage",+ version: "1.0.0",+ enabled: true,+ requiresPermission: false+ }));+ break;+ case "PROVIDER_ENABLE":+ this._handleProviderResponse(JSON.stringify({+ action: "PROVIDER_ENABLE",+ provider: "storage",+ hasPermission: true,+ success: true+ }));+ break;+ case "STORE":+ let keyValue = msg.key ? msg.key.trim() : null;++ if (!keyValue || keyValue.length === 0) {+ throw new Error("Storage provider 'store' action requires a `key`");+ }++ if (msg.hasOwnProperty("value")) {+ if (msg.value === null) {+ window.localStorage.removeItem(keyValue);+ } else {+ window.localStorage.setItem(keyValue, msg.value);+ }+ }++ break;+ case "RETRIEVE":+ keyValue = msg.key ? msg.key.trim() : null;++ if (!keyValue || keyValue.length === 0) {+ throw new Error("Storage provider 'retrieve' action requires a `key`");+ }++ this._handleProviderResponse(JSON.stringify({+ action: "RETRIEVE",+ provider: "storage",+ key: keyValue,+ value: window.localStorage.getItem(keyValue)+ }));+ break;+ default:+ throw new Error("Unsupported provider '" + msg.provider + "' and action '" + msg.action + "'");+ }+ break;+ }++ }+ }++ protected _callCompletedCallback() {+ let callback = this._enableCompleteCallback;+ this._enableCompleteCallback = null;+ if (callback) {+ window.setTimeout(() => {+ callback!()+ }, 0);+ }+ }++ protected static _createConsoleRegistration(): ConsoleRegistration {+ let reg: ConsoleRegistration = {+ name: platform.name,+ version: platform.version,+ platform: platform.os.toString(),+ apps: [],+ model: ((platform.manufacturer ? platform.manufacturer + " " : "") + (platform.product ? platform.product : "")).trim()+ };++ return reg;+ }++ protected async _initialiseProvider(providerName: string): Promise<ProviderInitialiseResponse> {+ console.debug("Console: initialising provider '" + providerName + "'");+ let initResponse = await this.sendProviderMessage({+ provider: providerName,+ action: "PROVIDER_INIT"+ }, true);++ this._registration.providers![providerName].version = initResponse.version;+ this._registration.providers![providerName].requiresPermission = initResponse.requiresPermission;+ this._registration.providers![providerName].hasPermission = initResponse.hasPermission;+ this._registration.providers![providerName].success = initResponse.success;+ this._registration.providers![providerName].enabled = initResponse.enabled;++ if (!initResponse.success) {+ console.debug("Provider initialisation failed: '" + providerName + "'");+ this._registration.providers![providerName].disabled = true;+ let index = this._pendingProviderEnables.indexOf(providerName);+ if (index >= 0) {+ this._pendingProviderEnables.splice(index, 1);+ }+ } else if (initResponse.enabled) {+ let index = this._pendingProviderEnables.indexOf(providerName);+ if (index >= 0) {+ this._pendingProviderEnables.splice(index, 1);+ }+ }++ return initResponse;+ }}\ No newline at end of filediff --git a/ui/component/core/src/index.ts b/ui/component/core/src/index.tsindex 656361fbc..b17700b0c 100644--- a/ui/component/core/src/index.ts+++ b/ui/component/core/src/index.ts@@ -7,7 +7,8 @@ export enum ORError {NONE = "NONE",MANAGER_FAILED_TO_LOAD = "MANAGER_FAILED_TO_LOAD",KEYCLOAK_FAILED_TO_LOAD = "KEYCLOAK_FAILED_TO_LOAD",- AUTH_TYPE_UNSUPPORTED = "AUTH_TYPE_UNSUPPORTED"+ AUTH_TYPE_UNSUPPORTED = "AUTH_TYPE_UNSUPPORTED",+ CONSOLE_ERROR = "CONSOLE_INIT_ERROR"}export enum Auth {@@ -43,7 +44,7 @@ export interface ManagerConfig {realm: string;autoLogin?: boolean;credentials?: Credentials;- consoleAutoEnable: boolean;+ consoleAutoEnable?: boolean;}export type EventCallback = (event: OREvent) => any;@@ -90,6 +91,10 @@ export class Manager {return this._error != null;}+ get console() {+ return this._console;+ }+protected static normaliseConfig(config: ManagerConfig): ManagerConfig {const normalisedConfig: ManagerConfig = Object.assign({}, config);@@ -117,19 +122,11 @@ export class Manager {}}- return normalisedConfig;- }+ if (!normalisedConfig.consoleAutoEnable) {+ normalisedConfig.consoleAutoEnable = true;+ }- // TODO: Implement console offline tokens- protected static getNativeOfflineRefreshToken(): string | null {- // if (this.console && this.console.enabled) {- // let storedToken = this.console.readNativeShellMessage('token');- // if (storedToken && storedToken.length > 0) {- // let storedTokenParsed = JSON.parse(storedToken);- // return storedTokenParsed.refreshToken;- // }- // }- return null;+ return normalisedConfig;}private _error: ORError = ORError.NONE;@@ -176,26 +173,30 @@ export class Manager {console.log("Already initialised");}- this._config = config = Manager.normaliseConfig(config);- const success = await this.doInit(config);+ this._config = Manager.normaliseConfig(config);+ let success = await this.doInit();if (success) {- this.doRestApiInit();+ success = this.doRestApiInit();}if (success) {- this._ready = true;- this.emitEvent(OREvent.READY);+ success = await this.doConsoleInit();}if (success) {- this.doConsoleInit();+ success = await this.doAuthInit();+ }++ if (success) {+ this._ready = true;+ this.emitEvent(OREvent.READY);}return success;}- protected async doInit(config: ManagerConfig): Promise<boolean> {+ protected async doInit(): Promise<boolean> {// Check manager exists by calling the info endpointtry {const json = await new Promise<any>((resolve, reject) => {@@ -210,73 +211,75 @@ export class Manager {oReq.send();});this._managerVersion = json && json.version ? json.version : "";+ return true;} catch (e) {// TODO: Implement auto retry?- console.info("Failed to contact the manager", e);+ console.error("Failed to contact the manager", e);this.setError(ORError.MANAGER_FAILED_TO_LOAD);- this.emitEvent(OREvent.INIT);return false;}+ }- switch (config.auth) {+ protected async doAuthInit(): Promise<boolean> {+ let success = true;+ switch (this._config.auth) {case Auth.BASIC:// TODO: Implement Basic auth support+ if (this._config.credentials) {+ rest.setBasicAuth(this._config.credentials.username, this._config.credentials.password);+ }this.setError(ORError.AUTH_TYPE_UNSUPPORTED);- this.emitEvent(OREvent.INIT);- return false;+ success = false;+ break;case Auth.KEYCLOAK:- const success = await this.loadAndInitialiseKeycloak(config);- this.emitEvent(OREvent.INIT);- return success;+ success = await this.loadAndInitialiseKeycloak();+ // Add interceptor to inject authorization header on each request+ rest.addRequestInterceptor(+ (config: AxiosRequestConfig) => {+ if (!config.headers.Authorization) {+ const token = this.getKeycloakToken();++ if (token) {+ config.headers.Authorization = "Bearer " + token;+ }+ }++ return config;+ }+ );+ break;case Auth.NONE:// Nothing for us to do here- this.emitEvent(OREvent.INIT);- return true;+ break;default:this.setError(ORError.AUTH_TYPE_UNSUPPORTED);- this.emitEvent(OREvent.INIT);- return false;+ success = false;+ break;}- }- protected doRestApiInit() {+ return success;+ }+ protected doRestApiInit(): boolean {rest.setTimeout(10000);rest.initialise(this.getBaseUrl());-- if (this._config.auth === Auth.BASIC && this._config.credentials) {- rest.setBasicAuth(this._config.credentials.username, this._config.credentials.password);- } else if (this._config.auth === Auth.KEYCLOAK) {- // Add interceptor to inject authorization header on each request- rest.addRequestInterceptor(- (config) => {- if (!config.headers.Authorization) {- const token = this.getKeycloakToken();-- if (token) {- config.headers.Authorization = "Bearer " + token;- }- }-- return config;- }- );- }+ return true;}- protected async doConsoleInit() {- let orConsole = new Console(this._config.realm, this._config.consoleAutoEnable, () => {- this._console.sendRegistration();- this.emitEvent(OREvent.CONSOLE_READY);- });-- this._console = orConsole;+ protected async doConsoleInit(): Promise<boolean> {+ try {+ let orConsole = new Console(this._config.realm, this._config.consoleAutoEnable!, () => {+ this.emitEvent(OREvent.CONSOLE_READY);+ });- await orConsole.initialise();- this.emitEvent(OREvent.CONSOLE_INIT);+ this._console = orConsole;- if (orConsole.autoEnable && orConsole.pendingProviderEnables.length > 0) {- await orConsole.enableProviders();+ await orConsole.initialise();+ this.emitEvent(OREvent.CONSOLE_INIT);+ return true;+ } catch (e) {+ this.setError(ORError.CONSOLE_ERROR);+ return false;}}@@ -300,6 +303,9 @@ export class Manager {public logout(redirectUrl?: string) {if (this._keycloak) {+ if (this.console.isMobile) {+ this.console.storeData("REFRESH_TOKEN", null);+ }const options = redirectUrl && redirectUrl !== "" ? {redirectUri: redirectUrl} : null;this._keycloak.logout(options);}@@ -346,6 +352,11 @@ export class Manager {return baseUrl;}+ public getAppName(): string {+ let pathArr = location.pathname.split('/');+ return pathArr.length >= 1 ? pathArr[1] : "";+ }+public hasRole(role: string) {return this._roles && this._roles.indexOf(role) >= 0;}@@ -372,25 +383,33 @@ export class Manager {return undefined;}- // TODO: Native shell support- protected isNative(): boolean {- // return this.console && this.console.enabled;- return false;+ protected isMobile(): boolean {+ return this.console && this.console.isMobile;}- protected onAuthenticated() {+ protected _onAuthenticated() {+ // If native shell is enabled, we need an offline refresh token+ if (this.console && this.console.isMobile && this.config.auth === Auth.KEYCLOAK) {+ if (this._keycloak.refreshTokenParsed.typ === "Offline") {+ console.debug("Storing offline refresh token");+ this.console.storeData("REFRESH_TOKEN", this._keycloak.refreshToken);+ } else {+ console.debug("No offline refresh token available");+ this.console.storeData("REFRESH_TOKEN", null);+ }+ }}// NOTE: The below works with Keycloak 2.x JS API - They made breaking changes in newer versions// so this will need updating.- protected async loadAndInitialiseKeycloak(config: ManagerConfig): Promise<boolean> {+ protected async loadAndInitialiseKeycloak(): Promise<boolean> {// Load the keycloak JS APIconst promise = new Promise<Event>((resolve, reject) => {// Load keycloak script from keycloak serverconst scriptElement = document.createElement("script");- scriptElement.src = config.keycloakUrl + "/js/keycloak.js";+ scriptElement.src = this._config.keycloakUrl + "/js/keycloak.js";scriptElement.onload = (e) => resolve(e);scriptElement.onerror = (e) => reject(e);document.querySelector("head")!.appendChild(scriptElement);@@ -408,8 +427,8 @@ export class Manager {// Initialise keycloakthis._keycloak = (window as any).Keycloak({clientId: "openremote",- realm: config.realm,- url: config.keycloakUrl+ realm: this._config.realm,+ url: this._config.keycloakUrl});this._keycloak.onAuthSuccess = () => {@@ -426,13 +445,16 @@ export class Manager {// so putting a check in place; wrap keycloak promise in proper ES6 promiselet keycloakPromise: any = null;try {+ // Try to use a stored offline refresh token if defined+ let offlineToken = await this.getNativeOfflineRefreshToken();+const authenticated = await new Promise<boolean>(((resolve, reject) => {keycloakPromise = resolve;this._keycloak.init({checkLoginIframe: false, // Doesn't work well with offline tokens- onLoad: config.autoLogin ? "login-required" : "check-sso",- refreshToken: Manager.getNativeOfflineRefreshToken(), // Try to use a stored offline refresh token- scope: this.isNative() ? "offline_access" : null+ onLoad: this._config.autoLogin ? "login-required" : "check-sso",+ refreshToken: offlineToken,+ scope: this.isMobile() ? "offline_access" : null}).success((auth: boolean) => {resolve(auth);}).error(() => {@@ -456,7 +478,7 @@ export class Manager {this._keycloakUpdateTokenInterval = setInterval(() => {this.updateKeycloakAccessToken();}, 10000);- this.onAuthenticated();+ this._onAuthenticated();}this.setAuthenticated(authenticated);return true;@@ -471,27 +493,6 @@ export class Manager {}}- // TODO: Implement console offline tokens- protected storeNativeOfflineRefreshToken() {- // // If native shell is enabled, we need an offline refresh token- // if (this.console && this.console.enabled) {- //- // // If we don't have an offline refresh token, try to get one- // if (this.keycloak.refreshTokenParsed.typ !== "Offline") {- // console.debug("Native shell enabled, requesting offline refresh token")- // this.doKeycloakLogin()- // return;- // }- //- // // Transfer offline refresh token to native shell so it can be stored for future usage- // console.debug("Native shell enabled, storing offline refresh token");- // this.console.postNativeShellMessage({- // type: 'token',- // data: {refreshToken: this.keycloak.refreshToken}- // });- // }- }-protected updateKeycloakAccessToken(): Promise<boolean> {// Access token must be good for X more seconds, should be half of Constants.ACCESS_TOKEN_LIFESPAN_SECONDSreturn new Promise<boolean>(() => {@@ -511,6 +512,17 @@ export class Manager {});}+ protected async getNativeOfflineRefreshToken(): Promise<string | null> {+ if (this.console && this.console.isMobile) {+ return await this.console.sendProviderMessage({+ provider: "storage",+ action: "RETRIEVE",+ key: "REFRESH_TOKEN"+ }, true);+ }+ return null;+ }+protected emitEvent(event: OREvent) {window.setTimeout(() => {for (const listener of this._listeners) {diff --git a/ui/demo/demo-core/src/index.ts b/ui/demo/demo-core/src/index.tsindex 0d85f1a1e..0e6a1514c 100644--- a/ui/demo/demo-core/src/index.ts+++ b/ui/demo/demo-core/src/index.ts@@ -15,10 +15,10 @@ let mainTemplate = (openremote: Manager) => html`<p><b>Roles: </b> ${openremote.roles ? openremote.roles.join(", ") : ""}</p><p><b>Is Super User: </b> ${openremote.isSuperUser()}</p><p><b>Is Manager Same Origin: </b> ${openremote.isManagerSameOrigin()}</p>-<p><b>Is Error: </b> ${openremote.isError}</p><p><b>Error:</b> ${openremote.error}</p><p><b>Config: </b> ${openremote.config ? JSON.stringify(openremote.config) : ""}</p>+<p><b>Console Registration: </b>${openremote.console ? JSON.stringify(openremote.console.registration) : ""}</p>`;function refresh() {@@ -30,10 +30,9 @@ openremote.addListener(event => {});openremote.init({- managerUrl: "http://localhost:8080",- keycloakUrl: "http://localhost:8080/auth",+ managerUrl: "http://192.168.1.85:8080",+ keycloakUrl: "http://192.168.1.85:8080/auth",auth: Auth.KEYCLOAK,autoLogin: false,- realm: "master",- consoleAutoEnable: true+ realm: "master"}).then(refresh);\ No newline at end of file