Skip to content

armgit / core

Public Imported from GitHub
0

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

Refactored openremote/core component and added console functionality

Rich Turnerfadf57d19498
diff --git a/client/src/main/webapp/src/or-app/or-console.html b/client/src/main/webapp/src/or-app/or-console.html
index 2c62004da..d10209546 100644
--- a/client/src/main/webapp/src/or-app/or-console.html
+++ b/client/src/main/webapp/src/or-app/or-console.html
@@ -123,8 +123,6 @@
ready() {
super.ready();
- this.$.queryParams.paramsString = window.location.search.slice(1);
- let queryParams = this.$.queryParams.paramsObject;
// If console query parameters set then they take precedence
if (queryParams.consoleName) {
diff --git a/console/android/src/main/java/org/openremote/android/MainActivity.java b/console/android/src/main/java/org/openremote/android/MainActivity.java
index 2aaca4141..27463e12c 100644
--- a/console/android/src/main/java/org/openremote/android/MainActivity.java
+++ b/console/android/src/main/java/org/openremote/android/MainActivity.java
@@ -602,7 +602,7 @@ public class MainActivity extends Activity {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
- webView.evaluateJavascript(String.format("openremote.INSTANCE.console.handleProviderResponse('%s')", jsonString), null);
+ webView.evaluateJavascript(String.format("OpenRemoteConsole.handleProviderResponse('%s')", jsonString), null);
}
});
} catch (JsonProcessingException e) {
diff --git a/console/iOS/ORLib/ORLib/ORViewController.swift b/console/iOS/ORLib/ORLib/ORViewController.swift
index 1ab2c968f..68b8806d2 100644
--- a/console/iOS/ORLib/ORLib/ORViewController.swift
+++ b/console/iOS/ORLib/ORLib/ORViewController.swift
@@ -113,7 +113,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
options: []) {
let theJSONText = String(data: theJSONData,
encoding: .utf8)
- let returnMessage = "openremote.INSTANCE.console.handleProviderResponse('\(theJSONText ?? "null")')"
+ let returnMessage = "OpenRemoteConsole.handleProviderResponse('\(theJSONText ?? "null")')"
DispatchQueue.main.async {
self.myWebView?.evaluateJavaScript("\(returnMessage)", completionHandler: { (any, error) in
print("JSON string = \(theJSONText!)")
diff --git a/model/src/main/java/org/openremote/model/console/ConsoleProvider.java b/model/src/main/java/org/openremote/model/console/ConsoleProvider.java
index 7e2c99b78..e7687a655 100644
--- a/model/src/main/java/org/openremote/model/console/ConsoleProvider.java
+++ b/model/src/main/java/org/openremote/model/console/ConsoleProvider.java
@@ -32,6 +32,7 @@ public class ConsoleProvider {
protected String version;
protected boolean requiresPermission;
protected boolean hasPermission;
+ protected boolean success;
protected boolean disabled;
protected ObjectValue data;
@@ -39,11 +40,13 @@ public class ConsoleProvider {
public ConsoleProvider(@JsonProperty("version") String version,
@JsonProperty("requiresPermission") boolean requiresPermission,
@JsonProperty("hasPermission") boolean hasPermission,
+ @JsonProperty("success") boolean success,
@JsonProperty("disabled") boolean disabled,
@JsonProperty("data") ObjectValue data) {
this.version = version;
this.requiresPermission = requiresPermission;
this.hasPermission = hasPermission;
+ this.success = success;
this.disabled = disabled;
this.data = data;
}
@@ -60,6 +63,10 @@ public class ConsoleProvider {
return hasPermission;
}
+ public boolean isSuccess() {
+ return success;
+ }
+
public boolean isDisabled() {
return disabled;
}
@@ -78,9 +85,10 @@ public class ConsoleProvider {
boolean hasPermission = obj.getBoolean("hasPermission").orElse(!requiresPermission.get());
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, disabled, data));
+ return Optional.of(new ConsoleProvider(version.get(), requiresPermission.get(), hasPermission, success, disabled, data));
});
}
diff --git a/model/src/main/java/org/openremote/model/console/ConsoleRegistration.java b/model/src/main/java/org/openremote/model/console/ConsoleRegistration.java
index 13c25522b..2f11fb261 100644
--- a/model/src/main/java/org/openremote/model/console/ConsoleRegistration.java
+++ b/model/src/main/java/org/openremote/model/console/ConsoleRegistration.java
@@ -24,24 +24,90 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
+/**
+ * Encapsulates data about a console instance that is used to generate an {@link org.openremote.model.asset.Asset} of
+ * type {@link org.openremote.model.asset.AssetType#CONSOLE}. The console is considered the app used to view the web
+ * application (client), for example:
+ * <p>
+ * Google Chrome on Windows 10 64-bit used to view the manager and customerA applications would generate the following
+ * registration:
+ * <blockquote><pre>{@code
+ * {
+ * "name": "Chrome",
+ * "version": "71.0.3578.98",
+ * "platform": "Windows 10 64-bit",
+ * "model": null,
+ * "providers": {
+ * "push": {
+ * "data": {
+ * "token": "ASasm,sASKasjASasjASJas"
+ * },
+ * "version": "web",
+ * "disabled": false,
+ * "hasPermission": true,
+ * "requiresPermission": true
+ * }
+ * },
+ * "apps": {
+ * "manager": "1.0.0",
+ * "customerA": "1.0.0"
+ * }
+ * }</pre></blockquote>
+ * <p>
+ * An Android console app called "Smart City" on a Samsung Galaxy S9 running Android 8.0 would generate the following
+ * registration:
+ * <blockquote><pre>{@code
+ * {
+ * "name": "Smart City",
+ * "version": "1.0.0",
+ * "platform": "Android 8.0",
+ * "model": "Samsung Galaxy S9",
+ * "providers": {
+ * "push": {
+ * "data": {
+ * "token": "ASasm,sASKasjASasjASJas"
+ * },
+ * "version": "fcm",
+ * "disabled": false,
+ * "hasPermission": true,
+ * "requiresPermission": true
+ * },
+ * "geofence": {
+ * "version": "ORConsole",
+ * "disabled": false,
+ * "hasPermission": true,
+ * "requiresPermission": true
+ * }
+ * },
+ * "apps": {
+ * "smartcity": "1.0.0"
+ * }
+ * }</pre></blockquote>
+ */
public class ConsoleRegistration {
protected String id;
protected String name;
protected String version;
protected String platform;
+ protected String model;
protected Map<String, ConsoleProvider> providers;
+ protected Map<String, String> apps;
@JsonCreator
public ConsoleRegistration(@JsonProperty("id") String id,
@JsonProperty("name") String name,
@JsonProperty("version") String version,
@JsonProperty("platform") String platform,
- @JsonProperty("providers") Map<String, ConsoleProvider> providers) {
+ @JsonProperty("providers") Map<String, ConsoleProvider> providers,
+ @JsonProperty("model") String model,
+ @JsonProperty("apps") Map<String, String> apps) {
this.id = id;
this.name = name;
this.version = version;
this.platform = platform;
this.providers = providers;
+ this.model = model;
+ this.apps = apps;
}
public String getId() {
@@ -64,7 +130,15 @@ public class ConsoleRegistration {
return platform;
}
+ public String getModel() {
+ return model;
+ }
+
public Map<String, ConsoleProvider> getProviders() {
return providers;
}
+
+ public Map<String, String> getApps() {
+ return apps;
+ }
}
diff --git a/ui/component/core/package.json b/ui/component/core/package.json
index 5a73970b9..a0b2208e7 100644
--- a/ui/component/core/package.json
+++ b/ui/component/core/package.json
@@ -10,7 +10,12 @@
},
"author": "OpenRemote",
"license": "AGPL-3.0-or-later",
- "dependencies": {},
+ "dependencies": {
+ "platform": "^1.3.5",
+ "url-search-params-polyfill": "^5.0.0",
+ "@openremote/model": "1.0.0",
+ "@openremote/rest": "1.0.0"
+ },
"devDependencies": {
"tslint": "^5.11.0",
"typescript": "^3.1.6"
diff --git a/ui/component/core/src/console.ts b/ui/component/core/src/console.ts
new file mode 100644
index 000000000..14d6b856b
--- /dev/null
+++ b/ui/component/core/src/console.ts
@@ -0,0 +1,357 @@
+import {ConsoleRegistration} from "@openremote/model";
+import rest from "@openremote/rest";
+
+declare function require(name: string): any;
+
+// No ES6 module support in platform lib
+let platform = require('platform');
+
+export interface ProviderMessage {
+ provider: string;
+ action: string;
+ data?: any;
+}
+
+interface ProviderInitialiseResponse extends ProviderMessage {
+ version: string;
+ requiresPermission: boolean;
+ hasPermission: boolean;
+ success: boolean;
+}
+
+export interface ProviderEnableRequest extends ProviderMessage {
+ consoleId: string;
+}
+
+export interface ProviderEnableResponse extends ProviderMessage {
+ hasPermission: boolean;
+ success: boolean;
+}
+
+export class Console {
+
+ protected _realm: string;
+ private _registration: ConsoleRegistration;
+ private _autoEnable: boolean = false;
+ protected _initialised: boolean = false;
+ protected _initialiseInProgress: boolean = false;
+ protected _pendingProviderPromises: { [name: string]: ((response: any) => void) | null } = {};
+ private _pendingProviderEnables: string[] = [];
+ protected _enableCompleteCallback: (() => void) | null;
+
+ constructor(realm: string, autoEnable: boolean, enableComplete: () => void) {
+
+ this._realm = realm;
+ this._autoEnable = autoEnable;
+ this._enableCompleteCallback = enableComplete;
+
+ // Export this to the window to make it accessible from mobile webview code
+ // @ts-ignore
+ window.OpenRemoteConsole = this;
+
+ // Check for query parameters to override values
+ let queryParams = new URLSearchParams(window.location.search);
+ let consoleName = queryParams.get("consoleName");
+ let consoleVersion = queryParams.get("consoleVersion");
+ let consolePlatform = queryParams.get("consolePlatform");
+ 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(" ") : [];
+ this._pendingProviderEnables = consoleProviders && consoleProviders.length > 0 ? consoleProviders.split(" ") : [];
+
+ // Look for existing console registration in local storage or just create a new one
+ let consoleReg: ConsoleRegistration = Console._createConsoleRegistration();
+
+ let consoleRegStr = window.localStorage.getItem("OpenRemoteConsole:" + realm);
+ if (consoleRegStr) {
+ try {
+ consoleReg = JSON.parse(consoleRegStr) as ConsoleRegistration;
+ } catch (e) {
+ console.error("Failed to deserialise console registration");
+ }
+ }
+
+ let oldProviders = consoleReg.providers;
+ consoleReg.providers = {};
+
+ for (let providerName of requestedProviders) {
+ let provider = oldProviders && oldProviders.hasOwnProperty(providerName) ? oldProviders[providerName] : {disabled: false};
+ consoleReg.providers[providerName] = provider;
+ if (provider.disabled) {
+ let index = this._pendingProviderEnables.indexOf(providerName);
+ this._pendingProviderEnables.splice(index, 1);
+ }
+ }
+
+ this._registration = consoleReg;
+
+ if (consoleName) {
+ consoleReg.name = consoleName;
+ }
+ if (consoleVersion) {
+ consoleReg.version = consoleVersion;
+ }
+ if (consolePlatform) {
+ consoleReg.platform = consolePlatform;
+ }
+
+ if (autoEnableStr) {
+ this._autoEnable = autoEnableStr === "TRUE" || autoEnableStr === "true";
+ }
+ }
+
+ get registration(): ConsoleRegistration {
+ return this._registration;
+ }
+
+ public get autoEnable(): boolean {
+ return this._autoEnable;
+ }
+
+ get pendingProviderEnables(): string[] {
+ return this._pendingProviderEnables;
+ }
+
+ public get shellApple(): boolean {
+ // @ts-ignore
+ return navigator.platform.substr(0, 2) === 'iP' && window.webkit && window.webkit.messageHandlers;
+ }
+
+ public get shellAndroid(): boolean {
+ // @ts-ignore
+ return !!window.MobileInterface;
+ }
+
+ public get isMobile(): boolean {
+ return this.shellApple || this.shellAndroid;
+ }
+
+ public async initialise(): Promise<void> {
+ if (this._initialised || this._initialiseInProgress) {
+ return;
+ }
+
+ console.debug("Console: initialising");
+ this._initialiseInProgress = true;
+
+ try {
+ // Get an ID for this console if it doesn't have one
+ if (!this._registration.id) {
+ await this.sendRegistration();
+ }
+
+ 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);
+ }
+ }
+ }
+ }
+
+ this._initialised = true;
+ this._initialiseInProgress = false;
+
+ if (this._pendingProviderEnables.length === 0) {
+ let callback = this._enableCompleteCallback;
+ this._enableCompleteCallback = null;
+ if (callback) {
+ window.setTimeout(() => {
+ callback!()
+ }, 0);
+ }
+ }
+ } catch (e) {
+ console.error(e);
+ this._initialiseInProgress = false;
+ }
+ }
+
+ 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
+ public async enableProviders(): Promise<void> {
+ if (!this._initialised) {
+ throw new Error("Console must be initialised before enabling providers");
+ }
+
+ for (let providerName of this._pendingProviderEnables) {
+ await this.enableProvider(providerName);
+ }
+ }
+
+ public async enableProvider(provider: 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 + "'");
+ }
+
+ console.debug("Console: enabling provider '" + provider + "'");
+ let msg: ProviderEnableRequest = {
+ provider: provider,
+ action: "PROVIDER_ENABLE",
+ consoleId: this._registration.id!,
+ data
+ };
+ let response = await this.sendProviderMessage(msg, true);
+ let index = this._pendingProviderEnables.indexOf(provider);
+
+ if (index >= 0) {
+ this._pendingProviderEnables.splice(index, 1);
+ if (this._pendingProviderEnables.length === 0) {
+ let callback = this._enableCompleteCallback;
+ this._enableCompleteCallback = null;
+ if (callback) {
+ callback();
+ }
+ }
+ }
+
+ return response;
+ }
+
+ public async disableProvider(provider: string): Promise<ProviderMessage> {
+ if (!this._initialised) {
+ console.debug("Console must be initialised before disabling providers");
+ throw new Error("Console must be initialised before disabling providers");
+ }
+
+ if (!this._registration.providers!.hasOwnProperty(provider)) {
+ console.debug("Invalid console provider '" + provider + "'");
+ throw new Error("Invalid console provider '" + provider + "'");
+ }
+
+ console.debug("Console: disabling provider '" + provider + "'");
+
+ let response = await this.sendProviderMessage({
+ provider: provider,
+ action: "PROVIDER_DISABLE"
+ }, true);
+ this._registration.providers![provider].disabled = true;
+ return response;
+ }
+
+ public async sendProviderMessage(message: ProviderMessage, waitForResponse: boolean) : Promise<any> {
+ if (!this._registration.providers!.hasOwnProperty(message.provider)) {
+ console.debug("Invalid console provider '" + message.provider + "'");
+ throw new Error("Invalid console provider '" + message.provider + "'");
+ }
+
+ if (!waitForResponse) {
+ this._doSendProviderMessage(message);
+ return;
+ }
+
+ let promiseName = message.provider + message.action;
+
+ if (this._pendingProviderPromises[promiseName]) {
+ throw new Error("Message already pending for provider '" + name + "' with action '" + message.action + "'");
+ }
+
+ 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.)
+ }
+ }
+
+ 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 postNativeShellMessage(jsonMessage: any) {
+ if (this.shellAndroid) {
+ // @ts-ignore
+ return window.MobileInterface.postMessage(JSON.stringify(jsonMessage));
+ }
+ if (this.shellApple) {
+ // @ts-ignore
+ return window.webkit.messageHandlers.int.postMessage(jsonMessage);
+ }
+ }
+
+ 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) {
+ if (!msg) {
+ return;
+ }
+
+ let msgJson = JSON.parse(msg);
+ let name = msgJson.provider;
+ let action = msgJson.action;
+
+ let resolve = this._pendingProviderPromises[name+action];
+
+ if (resolve != null) {
+ this._pendingProviderPromises[name+action] = null;
+ resolve(msgJson);
+ }
+ }
+}
\ No newline at end of file
diff --git a/ui/component/core/src/index.ts b/ui/component/core/src/index.ts
index e5226e44c..656361fbc 100644
--- a/ui/component/core/src/index.ts
+++ b/ui/component/core/src/index.ts
@@ -1,3 +1,8 @@
+import 'url-search-params-polyfill';
+import {Console} from "./console";
+import rest from "@openremote/rest";
+import {AxiosRequestConfig} from 'axios';
+
export enum ORError {
NONE = "NONE",
MANAGER_FAILED_TO_LOAD = "MANAGER_FAILED_TO_LOAD",
@@ -15,7 +20,9 @@ export enum OREvent {
INIT = "INIT",
AUTHENTICATED = "AUTHENTICATED",
ERROR = "ERROR",
- READY = "READY"
+ READY = "READY",
+ CONSOLE_INIT = "CONSOLE_INIT",
+ CONSOLE_READY = "CONSOLE_READY"
}
export interface Credentials {
@@ -31,10 +38,12 @@ export interface LoginOptions {
export interface ManagerConfig {
managerUrl: string;
keycloakUrl?: string;
+ appVersion?: string;
auth?: Auth;
- realm?: string;
- autoLogin: boolean;
+ realm: string;
+ autoLogin?: boolean;
credentials?: Credentials;
+ consoleAutoEnable: boolean;
}
export type EventCallback = (event: OREvent) => any;
@@ -134,6 +143,7 @@ export class Manager {
private _keycloakUpdateTokenInterval?: number = undefined;
private _managerVersion: string = "";
private _listeners: EventCallback[] = [];
+ private _console!: Console;
public isManagerSameOrigin(): boolean {
if (!this.initialised) {
@@ -168,10 +178,20 @@ export class Manager {
this._config = config = Manager.normaliseConfig(config);
const success = await this.doInit(config);
+
+ if (success) {
+ this.doRestApiInit();
+ }
+
if (success) {
this._ready = true;
this.emitEvent(OREvent.READY);
}
+
+ if (success) {
+ this.doConsoleInit();
+ }
+
return success;
}
@@ -219,6 +239,47 @@ export class Manager {
}
}
+ protected doRestApiInit() {
+
+ 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;
+ }
+ );
+ }
+ }
+
+ protected async doConsoleInit() {
+ let orConsole = new Console(this._config.realm, this._config.consoleAutoEnable, () => {
+ this._console.sendRegistration();
+ this.emitEvent(OREvent.CONSOLE_READY);
+ });
+
+ this._console = orConsole;
+
+ await orConsole.initialise();
+ this.emitEvent(OREvent.CONSOLE_INIT);
+
+ if (orConsole.autoEnable && orConsole.pendingProviderEnables.length > 0) {
+ await orConsole.enableProviders();
+ }
+ }
+
public getLogoutUrl(redirectUrl?: string) {
if (this._keycloak) {
const options = redirectUrl && redirectUrl !== "" ? {redirectUri: redirectUrl} : null;
@@ -279,6 +340,12 @@ export class Manager {
return this.hasRole("admin");
}
+ public getBaseUrl() {
+ let baseUrl = this._config.managerUrl;
+ baseUrl += "/api/" + this._config.realm + "/";
+ return baseUrl;
+ }
+
public hasRole(role: string) {
return this._roles && this._roles.indexOf(role) >= 0;
}
@@ -445,9 +512,11 @@ export class Manager {
}
protected emitEvent(event: OREvent) {
- for (const listener of this._listeners) {
- listener(event);
- }
+ window.setTimeout(() => {
+ for (const listener of this._listeners) {
+ listener(event);
+ }
+ }, 0);
}
protected setError(error: ORError) {
diff --git a/ui/component/core/tsconfig.json b/ui/component/core/tsconfig.json
index badeac3f8..fd70e8e76 100644
--- a/ui/component/core/tsconfig.json
+++ b/ui/component/core/tsconfig.json
@@ -6,5 +6,8 @@
},
"include": [
"./src"
+ ],
+ "references": [
+ { "path": "../rest" }
]
}
\ No newline at end of file
diff --git a/ui/component/rest/package.json b/ui/component/rest/package.json
index 910337fe2..7b0d8dd03 100644
--- a/ui/component/rest/package.json
+++ b/ui/component/rest/package.json
@@ -11,7 +11,6 @@
"author": "OpenRemote",
"license": "AGPL-3.0-or-later",
"dependencies": {
- "@openremote/core": "^1.0.0",
"@openremote/model": "^1.0.0",
"axios": "^0.18.0"
},
diff --git a/ui/component/rest/src/index.ts b/ui/component/rest/src/index.ts
index 99483caa5..8899630e4 100644
--- a/ui/component/rest/src/index.ts
+++ b/ui/component/rest/src/index.ts
@@ -1,69 +1,36 @@
-import openremote, {Auth, OREvent} from "@openremote/core";
-import axios, {AxiosInstance} from "axios";
+import axios, {AxiosInstance, AxiosRequestConfig} from "axios";
import {ApiClient} from "./restclient";
-import {Promise} from "es6-promise";
-class RestApi {
+export class RestApi {
get api() {
return this._client;
}
- protected static getBaseUrl(): string {
- let baseUrl = openremote.config.managerUrl;
- baseUrl += "/api/" + openremote.config.realm + "/";
- return baseUrl;
- }
-
protected _client!: ApiClient;
protected _axiosInstance!: AxiosInstance;
constructor() {
- openremote.addListener((evt) => this.onEvent(evt));
- this.initClient();
+ this._axiosInstance = axios.create();
}
- protected onEvent(event: OREvent) {
- switch (event) {
- case OREvent.AUTHENTICATED:
- break;
- case OREvent.ERROR:
- break;
- case OREvent.INIT:
- this.initClient();
- break;
- }
+ public setTimeout(timeout: number) {
+ this._axiosInstance.defaults.timeout = timeout;
}
- protected initClient() {
- if (!this._client && openremote.initialised && openremote.isManagerAvailable) {
- this._axiosInstance = axios.create();
- this._axiosInstance.defaults.timeout = 10000;
-
- if (openremote.config.auth === Auth.BASIC && openremote.config.credentials) {
- this._axiosInstance.defaults.auth = {
- password: openremote.config.credentials.password,
- username: openremote.config.credentials.username
- };
- } else if (openremote.config.auth === Auth.KEYCLOAK) {
- // Add interceptor to inject authorization header on each request
- this._axiosInstance.interceptors.request.use(
- (config) => {
- if (!config.headers.Authorization) {
- const token = openremote.getKeycloakToken();
+ public setBasicAuth(username: string, password: string) {
+ this._axiosInstance.defaults.auth = {
+ password: password,
+ username: username
+ };
+ }
- if (token) {
- config.headers.Authorization = "Bearer " + token;
- }
- }
+ public addRequestInterceptor(interceptor: (config: AxiosRequestConfig) => AxiosRequestConfig) {
+ this._axiosInstance.interceptors.request.use(interceptor);
+ }
- return config;
- },
- (error) => Promise.reject(error)
- );
- }
- this._client = new ApiClient(RestApi.getBaseUrl(), this._axiosInstance);
- }
+ public initialise(baseUrl: string) {
+ this._client = new ApiClient(baseUrl, this._axiosInstance);
}
}
diff --git a/ui/component/rest/tsconfig.json b/ui/component/rest/tsconfig.json
index d1a0af415..badeac3f8 100644
--- a/ui/component/rest/tsconfig.json
+++ b/ui/component/rest/tsconfig.json
@@ -6,8 +6,5 @@
},
"include": [
"./src"
- ],
- "references": [
- { "path": "../core" }
]
}
\ No newline at end of file
diff --git a/ui/demo/demo-core/.gitignore b/ui/demo/demo-core/.gitignore
new file mode 100644
index 000000000..9fde23e0a
--- /dev/null
+++ b/ui/demo/demo-core/.gitignore
@@ -0,0 +1,3 @@
+src/**/*.d.ts
+src/**/*.js.map
+src/**/*.js
\ No newline at end of file
diff --git a/ui/demo/demo-core/src/index.ts b/ui/demo/demo-core/src/index.ts
index 4c80f194f..0d85f1a1e 100644
--- a/ui/demo/demo-core/src/index.ts
+++ b/ui/demo/demo-core/src/index.ts
@@ -34,5 +34,6 @@ openremote.init({
keycloakUrl: "http://localhost:8080/auth",
auth: Auth.KEYCLOAK,
autoLogin: false,
- realm: "master"
+ realm: "master",
+ consoleAutoEnable: true
}).then(refresh);
\ No newline at end of file
diff --git a/ui/demo/demo-core/webpack.config.js b/ui/demo/demo-core/webpack.config.js
index b3a44ccb7..9e59c5346 100644
--- a/ui/demo/demo-core/webpack.config.js
+++ b/ui/demo/demo-core/webpack.config.js
@@ -1,49 +1,15 @@
-
var HtmlWebpackPlugin = require("html-webpack-plugin");
-// The below was an attempt to get native ES6 module support alongside bundled JS modules but due to lack
-// of understanding about webpack internals and poor docs given up for now and will just rely on bundles.
-// class ES6Plugin {
-// apply(compiler) {
-// compiler.hooks.normalModuleFactory.tap(
-// "NormalModuleReplacementPlugin",
-// nmf => {
-// nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => {
-// if (!result) return;
-// if (/node_modules/.test(result.request)) {
-// let relPath = path.relative(__dirname, result.request);
-// let dest = relPath.split(path.sep);
-// while(dest.length > 0 && dest[0] !== 'node_modules') {
-// dest.shift();
-// }
-// dest.shift();
-// dest = path.join(compiler.options.output.path, 'modules', dest.join(path.sep));
-// fs.mkdirsSync(path.dirname(dest));
-// fs.copySync(result.request, dest, {overwrite: true});
-// result.resource = dest;
-// } else {
-// console.log(result.request);
-// }
-// return result;
-// });
-// }
-// );
-// }
-// }
module.exports = {
mode: 'development',
entry: {
- 'bundle': './src/index.ts'
+ 'bundle': './src/index.js'
},
output: {
- path: __dirname + "/dist",
+ path: __dirname + "/dist",
filename: "[name].[hash].js",
publicPath: ""
},
- resolve: {
- extensions: [ '.tsx', '.ts', '.js' ],
- mainFields: ['types', 'browser', 'module', 'main']
- },
devtool: 'inline-source-map',
devServer: {
port: 9000,
@@ -59,24 +25,37 @@ module.exports = {
module: {
rules: [
{
- test: /\.tsx?$/,
- use: [
- {
- loader: "awesome-typescript-loader",
- }
+ test: /\.js$/,
+ use: ["source-map-loader"],
+ enforce: "pre",
+ exclude: [
+ /node_modules/
]
},
{
test: /\.js$/,
- exclude: /webcomponentsjs/,
+ include: function(modulePath) {
+ return /(@webcomponents[\/|\\]shadycss|lit-css|styled-lit-element|lit-html|@polymer|@lit|pwa-helpers)/.test(modulePath) || !/node_modules/.test(modulePath);
+ },
use: [
{
- loader: 'babel-loader',
- options: {
- presets: ['@babel/preset-env']
- }
+ loader: 'babel-loader'
}
]
+ },
+ {
+ test: /\.css$/,
+ use: [
+ { loader: "css-loader" }
+ ]
+ },
+ {
+ test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
+ loader: 'url-loader',
+ options: {
+ outputPath: "images/",
+ limit: 10000,
+ },
}
]
}
diff --git a/ui/yarn.lock b/ui/yarn.lock
index 73c1f57c7..82459365f 100644
--- a/ui/yarn.lock
+++ b/ui/yarn.lock
@@ -4772,6 +4772,11 @@ pkg-dir@^3.0.0:
dependencies:
find-up "^3.0.0"
+platform@^1.3.5:
+ version "1.3.5"
+ resolved "https://registry.yarnpkg.com/platform/-/platform-1.3.5.tgz#fb6958c696e07e2918d2eeda0f0bc9448d733444"
+ integrity sha512-TuvHS8AOIZNAlE77WUDiR4rySV/VMptyMfcfeoMgs4P8apaZM3JrnbzBiixKUv+XR6i+BXrQh8WAnjaSPFO65Q==
+
portfinder@^1.0.9:
version "1.0.19"
resolved "https://registry.yarnpkg.com/portfinder/-/portfinder-1.0.19.tgz#07e87914a55242dcda5b833d42f018d6875b595f"
@@ -6083,6 +6088,11 @@ url-parse@^1.4.3:
querystringify "^2.0.0"
requires-port "^1.0.0"
+url-search-params-polyfill@^5.0.0:
+ version "5.0.0"
+ resolved "https://registry.yarnpkg.com/url-search-params-polyfill/-/url-search-params-polyfill-5.0.0.tgz#09b98337c89dcf6c6a6a0bfeb096f6ba83b7526b"
+ integrity sha512-+SCD22QJp4UnqPOI5UTTR0Ljuh8cHbjEf1lIiZrZ8nHTlTixqwVsVQTSfk5vrmDz7N09/Y+ka5jQr0ff35FnQQ==
+
url@^0.11.0:
version "0.11.0"
resolved "https://registry.yarnpkg.com/url/-/url-0.11.0.tgz#3838e97cfc60521eb73c525a8e55bfdd9e2e28f1"