@openremote/core 1.8.0-snapshot.20250725070921 → 1.8.0-snapshot.20250725120000

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/console.js CHANGED
@@ -1 +1,541 @@
1
- var __awaiter=this&&this.__awaiter||function(e,i,r,s){return new(r||(r=Promise))(function(t,o){function n(e){try{d(s.next(e))}catch(e){o(e)}}function a(e){try{d(s.throw(e))}catch(e){o(e)}}function d(e){var i;e.done?t(e.value):((i=e.value)instanceof r?i:new r(function(e){e(i)})).then(n,a)}d((s=s.apply(e,i||[])).next())})};import e from"./index";import{Deferred as i}from"./util";let platform=require("platform");export class Console{constructor(i,r,s){this._autoEnable=!1,this._initialised=!1,this._initialiseInProgress=!1,this._pendingProviderPromises={},this._providerMessageListeners={},this._pendingProviderEnables=[],this._registrationTimer=null,this._realm=i,this._autoEnable=r,this._enableCompleteCallback=s,window.OpenRemoteConsole=this;let t=new URLSearchParams(window.location.search),o=t.get("consoleName"),n=t.get("consoleVersion"),a=t.get("consolePlatform"),d=t.get("consoleProviders"),l=t.get("consoleAutoEnable"),p=d&&d.length>0?d.split(" "):["push"];this._pendingProviderEnables=p;let h=Console._createConsoleRegistration(),g=window.localStorage.getItem("OpenRemoteConsole:"+i);if(g)try{let e=JSON.parse(g);e.id&&(h.id=e.id),e.name&&(h.name=e.name),e.providers&&(h.providers=e.providers),e.apps&&(h.apps=e.apps)}catch(e){console.error("Failed to deserialise console registration")}let v=h.providers;for(let e of(h.providers={},p)){let i=v&&v.hasOwnProperty(e)?v[e]:{enabled:!1,disabled:!1};h.providers[e]=i}let c=e.getAppName();c.length>0&&0>h.apps.indexOf(c)&&h.apps.push(c),this._registration=h,o&&(h.name=o),n&&(h.version=n),a&&(h.platform=a),l&&(this._autoEnable="TRUE"===l||"true"===l)}get registration(){return this._registration}get autoEnable(){return this._autoEnable}get pendingProviderEnables(){return this._pendingProviderEnables.slice(0)}get shellApple(){let e=navigator.userAgentData&&navigator.userAgentData.platform?navigator.userAgentData.platform:navigator.platform;return e&&("iP"===e.substring(0,2)||"Mac"===e.substring(0,3))&&window.webkit&&window.webkit.messageHandlers}get shellAndroid(){return!!window.MobileInterface}get isMobile(){return this.shellApple||this.shellAndroid}initialise(){return __awaiter(this,void 0,void 0,function*(){if(!this._initialised&&!this._initialiseInProgress){console.debug("Console: initialising"),this._initialiseInProgress=!0;try{if(this._registration.providers)for(let e of Object.keys(this._registration.providers))yield this._initialiseProvider(e);this._registration.id||(yield this.sendRegistration(0)),this._initialised=!0,this._initialiseInProgress=!1,0===this._pendingProviderEnables.length?(yield this.sendRegistration(),this._callCompletedCallback()):this._autoEnable&&(yield this.enableProviders())}catch(e){console.error(e)}finally{this._initialiseInProgress=!1}}})}enableProviders(){return __awaiter(this,void 0,void 0,function*(){if(!this._initialised)throw Error("Console must be initialised before enabling providers");for(let e=this._pendingProviderEnables.length-1;e>-1;e--){let i=this._pendingProviderEnables[e];yield this.enableProvider(i)}})}enableProvider(e,i){return __awaiter(this,void 0,void 0,function*(){if(!this._initialised)throw console.debug("Console must be initialised before disabling providers"),Error("Console must be initialised before enabling providers");if(!this._registration.providers.hasOwnProperty(e))throw console.debug("Invalid console provider '"+e+"'"),Error("Invalid console provider '"+e+"'");console.debug("Console: enabling provider '"+e+"'");let r={provider:e,action:"PROVIDER_ENABLE",consoleId:this._registration.id,data:i},s=yield this.sendProviderMessage(r,!0);this._registration.providers[e].hasPermission=s.hasPermission,this._registration.providers[e].success=s.success,this._registration.providers[e].enabled=s.success,this._registration.providers[e].data=s.data;let t=this._pendingProviderEnables.indexOf(e);return t>=0&&(this._pendingProviderEnables.splice(t,1),0===this._pendingProviderEnables.length&&(this.sendRegistration(),this._callCompletedCallback())),s})}disableProvider(e){return __awaiter(this,void 0,void 0,function*(){if(!this._initialised)throw console.debug("Console must be initialised before disabling providers"),Error("Console must be initialised before disabling providers");if(!this._registration.providers.hasOwnProperty(e))throw console.debug("Invalid console provider '"+e+"'"),Error("Invalid console provider '"+e+"'");console.debug("Console: disabling provider '"+e+"'");let i=yield this.sendProviderMessage({provider:e,action:"PROVIDER_DISABLE"},!0);return this._registration.providers[e].disabled=!0,this._registration.providers[e].enabled=!1,i})}getProvider(e){return this._registration&&this._registration.providers?this._registration.providers[e]:void 0}sendProviderMessage(e,r){return __awaiter(this,void 0,void 0,function*(){if("storage"!==e.provider&&!this._registration.providers.hasOwnProperty(e.provider))throw console.debug("Invalid console provider '"+e.provider+"'"),Error("Invalid console provider '"+e.provider+"'");if(!r)return void this._doSendProviderMessage(e);let s=e.provider+e.action;if(this._pendingProviderPromises[s])throw Error("Message already pending for provider '"+e.provider+"' with action '"+e.action+"'");let t=new i;return this._pendingProviderPromises[s]=[t,window.setTimeout(()=>{delete this._pendingProviderPromises[s],t.reject("No response from provider")},5e3)],this._doSendProviderMessage(e),t.promise})}sendRegistration(i){return this._registrationTimer&&(window.clearTimeout(this._registrationTimer),this._registrationTimer=null),console.debug("Sending registration in: "+(i=void 0!==i?i:2e3)+"ms"),new Promise((i,r)=>{this._registrationTimer=window.setTimeout(()=>{this._registrationTimer=null,console.debug("Console: updating registration");try{this._registration.name||(this._registration.name="Console"),this._registration.platform||(this._registration.platform="N/A"),this._registration.version||(this._registration.version="N/A"),this._registration.providers||(this._registration.providers={}),e.rest.api.ConsoleResource.register(this._registration).then(e=>{if(200!==e.status)throw Error("Failed to register console");this._registration=e.data,console.debug("Console: registration successful"),console.debug("Console: updating locally stored registration"),window.localStorage.setItem("OpenRemoteConsole:"+this._realm,JSON.stringify(this._registration)),i()})}catch(e){console.error("Failed to register console"),r("Failed to register console")}})})}storeData(e,i){this.sendProviderMessage({provider:"storage",action:"STORE",key:e,value:i},!1)}retrieveData(e){return __awaiter(this,void 0,void 0,function*(){let i=this.sendProviderMessage({provider:"storage",action:"RETRIEVE",key:e},!0);try{let e=yield Promise.race([i,new Promise((e,i)=>setTimeout(i,2e3))]);if(e&&e.value){let i=e.value;return"null"===i?void 0:i}}catch(e){console.log("Failed to retrieve data from storage provider")}})}addProviderMessageListener(e,i){this._providerMessageListeners[e.provider+e.action]=i}removeProviderMessageListener(e){delete this._providerMessageListeners[e.provider+e.action]}_postNativeShellMessage(e){try{if(this.shellAndroid)return window.MobileInterface.postMessage(JSON.stringify(e));if(this.shellApple)return window.webkit.messageHandlers.int.postMessage(e)}catch(e){console.error("Failed to send shell message towards console",e)}}_doSendGenericMessage(e,i){let r={type:e,data:i};this.isMobile?this._postNativeShellMessage(r):console.warn("Failed to send generic message to console.",r)}_doSendProviderMessage(e){if(this.isMobile)this._postNativeShellMessage({type:"provider",data:e});else{if(!e.provider||!e.action)return;switch(e.provider.trim().toUpperCase()){case"PUSH":switch(e.action.trim().toUpperCase()){case"PROVIDER_INIT":this._handleProviderResponse(JSON.stringify({action:"PROVIDER_INIT",provider:"push",version:"web",enabled:!0,disabled:!1,hasPermission:!0,requiresPermission:!1,success:!0}));break;case"PROVIDER_ENABLE":this._handleProviderResponse(JSON.stringify({action:"PROVIDER_ENABLE",provider:"push",hasPermission:!0,success:!0}));break;default:throw Error("Unsupported provider '"+e.provider+"' and action '"+e.action+"'")}break;case"STORAGE":switch(e.action){case"PROVIDER_INIT":this._handleProviderResponse(JSON.stringify({action:"PROVIDER_INIT",provider:"storage",version:"1.0.0",disabled:!1,enabled:!0,hasPermission:!0,requiresPermission:!1,success:!0}));break;case"PROVIDER_ENABLE":this._handleProviderResponse(JSON.stringify({action:"PROVIDER_ENABLE",provider:"storage",hasPermission:!0,success:!0}));break;case"STORE":{let i=e.key?e.key.trim():null;if(!i||0===i.length)throw Error("Storage provider 'store' action requires a `key`");null===e.value?window.localStorage.removeItem(i):window.localStorage.setItem(i,JSON.stringify(e.value))}break;case"RETRIEVE":{let i=e.key?e.key.trim():null;if(!i||0===i.length)throw Error("Storage provider 'retrieve' action requires a `key`");let r=window.localStorage.getItem(i);if(null!==r)try{r=JSON.parse(r)}catch(e){}this._handleProviderResponse(JSON.stringify({action:"RETRIEVE",provider:"storage",key:i,value:r}))}break;default:throw Error("Unsupported provider '"+e.provider+"' and action '"+e.action+"'")}break;default:console.error("Unsupported provider: "+e.provider)}}}_handleProviderResponse(e){if(!e)return;let i=JSON.parse(e),r=i.provider,s=i.action,t=this._pendingProviderPromises[r+s];t&&(window.clearTimeout(t[1]),delete this._pendingProviderPromises[r+s],t[0].resolve(i));let o=this._providerMessageListeners[r+s];o&&o(i)}_callCompletedCallback(){let e=this._enableCompleteCallback;this._enableCompleteCallback=null,e&&window.setTimeout(()=>{e()},0)}static _createConsoleRegistration(){return{name:platform.name,version:platform.version,platform:platform.os.toString(),apps:[],model:((platform.manufacturer?platform.manufacturer+" ":"")+(platform.product?platform.product:"")).trim()}}_initialiseProvider(e){return __awaiter(this,void 0,void 0,function*(){let i;console.debug("Console: initialising provider '"+e+"'");try{i=yield this.sendProviderMessage({provider:e,action:"PROVIDER_INIT"},!0),this._registration.providers[e].version=i.version,this._registration.providers[e].requiresPermission=i.requiresPermission,this._registration.providers[e].hasPermission=i.hasPermission,this._registration.providers[e].success=i.success,this._registration.providers[e].enabled=i.enabled,this._registration.providers[e].disabled=i.disabled,this._registration.providers[e].data=i.data}catch(e){console.error(e),i={action:"",disabled:!1,enabled:!1,hasPermission:!1,provider:"",requiresPermission:!1,version:"",success:!1}}if(i.success||(console.debug("Provider initialisation failed: '"+e+"'"),i.disabled=!0,this._registration.providers[e].disabled=!0),i.disabled||i.enabled){let i=this._pendingProviderEnables.indexOf(e);i>=0&&this._pendingProviderEnables.splice(i,1)}})}}
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import manager from "./index";
11
+ import { Deferred } from "./util";
12
+ // No ES6 module support in platform lib
13
+ let platform = require('platform');
14
+ /**
15
+ * Storage provider is a special case that must always be available and doesn't require init/enable logic
16
+ */
17
+ export class Console {
18
+ constructor(realm, autoEnable, enableComplete) {
19
+ this._autoEnable = false;
20
+ this._initialised = false;
21
+ this._initialiseInProgress = false;
22
+ this._pendingProviderPromises = {};
23
+ this._providerMessageListeners = {};
24
+ this._pendingProviderEnables = [];
25
+ this._registrationTimer = null;
26
+ this._realm = realm;
27
+ this._autoEnable = autoEnable;
28
+ this._enableCompleteCallback = enableComplete;
29
+ // Export this to the window to make it accessible from mobile webview code
30
+ // @ts-ignore
31
+ window.OpenRemoteConsole = this;
32
+ // Check for query parameters to override values
33
+ let queryParams = new URLSearchParams(window.location.search);
34
+ let consoleName = queryParams.get("consoleName");
35
+ let consoleVersion = queryParams.get("consoleVersion");
36
+ let consolePlatform = queryParams.get("consolePlatform");
37
+ let consoleProviders = queryParams.get("consoleProviders");
38
+ let autoEnableStr = queryParams.get("consoleAutoEnable");
39
+ let requestedProviders = consoleProviders && consoleProviders.length > 0 ? consoleProviders.split(" ") : ["push"];
40
+ this._pendingProviderEnables = requestedProviders;
41
+ // Look for existing console registration in local storage or just create a new one
42
+ let consoleReg = Console._createConsoleRegistration();
43
+ let consoleRegStr = window.localStorage.getItem("OpenRemoteConsole:" + realm);
44
+ if (consoleRegStr) {
45
+ try {
46
+ let storedRegObj = JSON.parse(consoleRegStr);
47
+ let storedReg = storedRegObj;
48
+ if (storedReg.id) {
49
+ consoleReg.id = storedReg.id;
50
+ }
51
+ if (storedReg.name) {
52
+ consoleReg.name = storedReg.name;
53
+ }
54
+ if (storedReg.providers) {
55
+ consoleReg.providers = storedReg.providers;
56
+ }
57
+ if (storedReg.apps) {
58
+ consoleReg.apps = storedReg.apps;
59
+ }
60
+ }
61
+ catch (e) {
62
+ console.error("Failed to deserialise console registration");
63
+ }
64
+ }
65
+ let oldProviders = consoleReg.providers;
66
+ consoleReg.providers = {};
67
+ for (let providerName of requestedProviders) {
68
+ let provider = oldProviders && oldProviders.hasOwnProperty(providerName) ? oldProviders[providerName] : {
69
+ enabled: false,
70
+ disabled: false
71
+ };
72
+ consoleReg.providers[providerName] = provider;
73
+ }
74
+ let appName = manager.getAppName();
75
+ if (appName.length > 0 && consoleReg.apps.indexOf(appName) < 0) {
76
+ consoleReg.apps.push(appName);
77
+ }
78
+ this._registration = consoleReg;
79
+ if (consoleName) {
80
+ consoleReg.name = consoleName;
81
+ }
82
+ if (consoleVersion) {
83
+ consoleReg.version = consoleVersion;
84
+ }
85
+ if (consolePlatform) {
86
+ consoleReg.platform = consolePlatform;
87
+ }
88
+ if (autoEnableStr) {
89
+ this._autoEnable = autoEnableStr === "TRUE" || autoEnableStr === "true";
90
+ }
91
+ }
92
+ get registration() {
93
+ return this._registration;
94
+ }
95
+ get autoEnable() {
96
+ return this._autoEnable;
97
+ }
98
+ get pendingProviderEnables() {
99
+ return this._pendingProviderEnables.slice(0);
100
+ }
101
+ get shellApple() {
102
+ // @ts-ignore
103
+ const platform = navigator.userAgentData && navigator.userAgentData.platform ? navigator.userAgentData.platform : navigator.platform;
104
+ // @ts-ignore
105
+ return platform && (platform.substring(0, 2) === 'iP' || platform.substring(0, 3) === 'Mac') && window.webkit && window.webkit.messageHandlers;
106
+ }
107
+ get shellAndroid() {
108
+ // @ts-ignore
109
+ return !!window.MobileInterface;
110
+ }
111
+ get isMobile() {
112
+ return this.shellApple || this.shellAndroid;
113
+ }
114
+ initialise() {
115
+ return __awaiter(this, void 0, void 0, function* () {
116
+ if (this._initialised || this._initialiseInProgress) {
117
+ return;
118
+ }
119
+ console.debug("Console: initialising");
120
+ this._initialiseInProgress = true;
121
+ try {
122
+ if (this._registration.providers) {
123
+ for (let providerName of Object.keys(this._registration.providers)) {
124
+ yield this._initialiseProvider(providerName);
125
+ }
126
+ }
127
+ // Get an ID for this console if it doesn't have one
128
+ if (!this._registration.id) {
129
+ yield this.sendRegistration(0);
130
+ }
131
+ this._initialised = true;
132
+ this._initialiseInProgress = false;
133
+ if (this._pendingProviderEnables.length === 0) {
134
+ yield this.sendRegistration();
135
+ this._callCompletedCallback();
136
+ }
137
+ else if (this._autoEnable) {
138
+ yield this.enableProviders();
139
+ }
140
+ }
141
+ catch (e) {
142
+ console.error(e);
143
+ }
144
+ finally {
145
+ this._initialiseInProgress = false;
146
+ }
147
+ });
148
+ }
149
+ // This mechanism doesn't support sending extra data to the providers being enabled and it doesn't allow data
150
+ // to be retrieved from the replies; if that is required then providers should be manually enabled from the calling app
151
+ enableProviders() {
152
+ return __awaiter(this, void 0, void 0, function* () {
153
+ if (!this._initialised) {
154
+ throw new Error("Console must be initialised before enabling providers");
155
+ }
156
+ for (let index = this._pendingProviderEnables.length - 1; index > -1; index--) {
157
+ let providerName = this._pendingProviderEnables[index];
158
+ yield this.enableProvider(providerName);
159
+ }
160
+ });
161
+ }
162
+ enableProvider(providerName, data) {
163
+ return __awaiter(this, void 0, void 0, function* () {
164
+ if (!this._initialised) {
165
+ console.debug("Console must be initialised before disabling providers");
166
+ throw new Error("Console must be initialised before enabling providers");
167
+ }
168
+ if (!this._registration.providers.hasOwnProperty(providerName)) {
169
+ console.debug("Invalid console provider '" + providerName + "'");
170
+ throw new Error("Invalid console provider '" + providerName + "'");
171
+ }
172
+ console.debug("Console: enabling provider '" + providerName + "'");
173
+ let msg = {
174
+ provider: providerName,
175
+ action: "PROVIDER_ENABLE",
176
+ consoleId: this._registration.id,
177
+ data
178
+ };
179
+ let response = yield this.sendProviderMessage(msg, true);
180
+ this._registration.providers[providerName].hasPermission = response.hasPermission;
181
+ this._registration.providers[providerName].success = response.success;
182
+ this._registration.providers[providerName].enabled = response.success;
183
+ this._registration.providers[providerName].data = response.data;
184
+ let index = this._pendingProviderEnables.indexOf(providerName);
185
+ if (index >= 0) {
186
+ this._pendingProviderEnables.splice(index, 1);
187
+ if (this._pendingProviderEnables.length === 0) {
188
+ this.sendRegistration();
189
+ this._callCompletedCallback();
190
+ }
191
+ }
192
+ return response;
193
+ });
194
+ }
195
+ disableProvider(provider) {
196
+ return __awaiter(this, void 0, void 0, function* () {
197
+ if (!this._initialised) {
198
+ console.debug("Console must be initialised before disabling providers");
199
+ throw new Error("Console must be initialised before disabling providers");
200
+ }
201
+ if (!this._registration.providers.hasOwnProperty(provider)) {
202
+ console.debug("Invalid console provider '" + provider + "'");
203
+ throw new Error("Invalid console provider '" + provider + "'");
204
+ }
205
+ console.debug("Console: disabling provider '" + provider + "'");
206
+ let response = yield this.sendProviderMessage({
207
+ provider: provider,
208
+ action: "PROVIDER_DISABLE"
209
+ }, true);
210
+ this._registration.providers[provider].disabled = true;
211
+ this._registration.providers[provider].enabled = false;
212
+ return response;
213
+ });
214
+ }
215
+ getProvider(name) {
216
+ return this._registration && this._registration.providers ? this._registration.providers[name] : undefined;
217
+ }
218
+ sendProviderMessage(message, waitForResponse) {
219
+ return __awaiter(this, void 0, void 0, function* () {
220
+ if (message.provider !== "storage" && !this._registration.providers.hasOwnProperty(message.provider)) {
221
+ console.debug("Invalid console provider '" + message.provider + "'");
222
+ throw new Error("Invalid console provider '" + message.provider + "'");
223
+ }
224
+ if (!waitForResponse) {
225
+ this._doSendProviderMessage(message);
226
+ return;
227
+ }
228
+ let promiseName = message.provider + message.action;
229
+ if (this._pendingProviderPromises[promiseName]) {
230
+ throw new Error("Message already pending for provider '" + message.provider + "' with action '" + message.action + "'");
231
+ }
232
+ const deferred = new Deferred();
233
+ const cancel = () => {
234
+ delete this._pendingProviderPromises[promiseName];
235
+ deferred.reject("No response from provider");
236
+ };
237
+ this._pendingProviderPromises[promiseName] = [deferred, window.setTimeout(cancel, 5000)];
238
+ this._doSendProviderMessage(message);
239
+ return deferred.promise;
240
+ });
241
+ }
242
+ // Uses a delayed mechanism to avoid excessive calls to the server during enabling providers
243
+ sendRegistration(delay) {
244
+ if (this._registrationTimer) {
245
+ window.clearTimeout(this._registrationTimer);
246
+ this._registrationTimer = null;
247
+ }
248
+ delay = delay !== undefined ? delay : 2000;
249
+ console.debug("Sending registration in: " + delay + "ms");
250
+ return new Promise((resolve, reject) => {
251
+ this._registrationTimer = window.setTimeout(() => {
252
+ this._registrationTimer = null;
253
+ console.debug("Console: updating registration");
254
+ try {
255
+ // Ensure console name, platform, version and providers are not null
256
+ if (!this._registration.name) {
257
+ this._registration.name = "Console";
258
+ }
259
+ if (!this._registration.platform) {
260
+ this._registration.platform = "N/A";
261
+ }
262
+ if (!this._registration.version) {
263
+ this._registration.version = "N/A";
264
+ }
265
+ if (!this._registration.providers) {
266
+ this._registration.providers = {};
267
+ }
268
+ manager.rest.api.ConsoleResource.register(this._registration).then((response) => {
269
+ if (response.status !== 200) {
270
+ throw new Error("Failed to register console");
271
+ }
272
+ this._registration = response.data;
273
+ console.debug("Console: registration successful");
274
+ console.debug("Console: updating locally stored registration");
275
+ window.localStorage.setItem("OpenRemoteConsole:" + this._realm, JSON.stringify(this._registration));
276
+ resolve();
277
+ });
278
+ }
279
+ catch (e) {
280
+ console.error("Failed to register console");
281
+ reject("Failed to register console");
282
+ }
283
+ });
284
+ });
285
+ }
286
+ storeData(key, value) {
287
+ this.sendProviderMessage({
288
+ provider: "storage",
289
+ action: "STORE",
290
+ key: key,
291
+ value: value
292
+ }, false);
293
+ }
294
+ retrieveData(key) {
295
+ return __awaiter(this, void 0, void 0, function* () {
296
+ let responsePromise = this.sendProviderMessage({
297
+ provider: "storage",
298
+ action: "RETRIEVE",
299
+ key: key
300
+ }, true);
301
+ // This is here to deal with lack of response from storage provider
302
+ // Storage provider should respond quickly
303
+ try {
304
+ const response = yield Promise.race([responsePromise, new Promise((resolve, reject) => setTimeout(reject, 2000))]);
305
+ if (response && response.value) {
306
+ const value = response.value;
307
+ return value === "null" ? undefined : value;
308
+ }
309
+ }
310
+ catch (e) {
311
+ console.log("Failed to retrieve data from storage provider");
312
+ }
313
+ return undefined;
314
+ });
315
+ }
316
+ addProviderMessageListener(providerAction, listener) {
317
+ this._providerMessageListeners[providerAction.provider + providerAction.action] = listener;
318
+ }
319
+ removeProviderMessageListener(providerAction) {
320
+ delete this._providerMessageListeners[providerAction.provider + providerAction.action];
321
+ }
322
+ _postNativeShellMessage(jsonMessage) {
323
+ try {
324
+ if (this.shellAndroid) {
325
+ // @ts-ignore
326
+ return window.MobileInterface.postMessage(JSON.stringify(jsonMessage));
327
+ }
328
+ if (this.shellApple) {
329
+ // @ts-ignore
330
+ return window.webkit.messageHandlers.int.postMessage(jsonMessage);
331
+ }
332
+ }
333
+ catch (e) {
334
+ console.error("Failed to send shell message towards console", e);
335
+ }
336
+ }
337
+ /**
338
+ * Function that allows sending of custom types and messages towards the console.
339
+ * TODO: Will be improved in the future, see this GitHub issue; https://github.com/openremote/openremote/issues/1318
340
+ */
341
+ _doSendGenericMessage(type, msg) {
342
+ const payload = { type: type, data: msg };
343
+ if (this.isMobile) {
344
+ this._postNativeShellMessage(payload);
345
+ }
346
+ else {
347
+ console.warn("Failed to send generic message to console.", payload);
348
+ }
349
+ }
350
+ _doSendProviderMessage(msg) {
351
+ if (this.isMobile) {
352
+ this._postNativeShellMessage({ type: "provider", data: msg });
353
+ }
354
+ else {
355
+ if (!msg.provider || !msg.action) {
356
+ return;
357
+ }
358
+ switch (msg.provider.trim().toUpperCase()) {
359
+ // TODO: Implement web browser provider handling (web push etc.)
360
+ case "PUSH":
361
+ switch (msg.action.trim().toUpperCase()) {
362
+ case "PROVIDER_INIT":
363
+ let initResponse = {
364
+ action: "PROVIDER_INIT",
365
+ provider: "push",
366
+ version: "web",
367
+ enabled: true,
368
+ disabled: false,
369
+ hasPermission: true,
370
+ requiresPermission: false,
371
+ success: true
372
+ };
373
+ this._handleProviderResponse(JSON.stringify(initResponse));
374
+ break;
375
+ case "PROVIDER_ENABLE":
376
+ let enableResponse = {
377
+ action: "PROVIDER_ENABLE",
378
+ provider: "push",
379
+ hasPermission: true,
380
+ success: true
381
+ };
382
+ this._handleProviderResponse(JSON.stringify(enableResponse));
383
+ break;
384
+ default:
385
+ throw new Error("Unsupported provider '" + msg.provider + "' and action '" + msg.action + "'");
386
+ }
387
+ break;
388
+ case "STORAGE":
389
+ switch (msg.action) {
390
+ case "PROVIDER_INIT":
391
+ let initResponse = {
392
+ action: "PROVIDER_INIT",
393
+ provider: "storage",
394
+ version: "1.0.0",
395
+ disabled: false,
396
+ enabled: true,
397
+ hasPermission: true,
398
+ requiresPermission: false,
399
+ success: true
400
+ };
401
+ this._handleProviderResponse(JSON.stringify(initResponse));
402
+ break;
403
+ case "PROVIDER_ENABLE":
404
+ let enableResponse = {
405
+ action: "PROVIDER_ENABLE",
406
+ provider: "storage",
407
+ hasPermission: true,
408
+ success: true
409
+ };
410
+ this._handleProviderResponse(JSON.stringify(enableResponse));
411
+ break;
412
+ case "STORE":
413
+ {
414
+ let keyValue = msg.key ? msg.key.trim() : null;
415
+ if (!keyValue || keyValue.length === 0) {
416
+ throw new Error("Storage provider 'store' action requires a `key`");
417
+ }
418
+ if (msg.value === null) {
419
+ window.localStorage.removeItem(keyValue);
420
+ }
421
+ else {
422
+ window.localStorage.setItem(keyValue, JSON.stringify(msg.value));
423
+ }
424
+ }
425
+ break;
426
+ case "RETRIEVE":
427
+ {
428
+ let keyValue = msg.key ? msg.key.trim() : null;
429
+ if (!keyValue || keyValue.length === 0) {
430
+ throw new Error("Storage provider 'retrieve' action requires a `key`");
431
+ }
432
+ let val = window.localStorage.getItem(keyValue);
433
+ if (val !== null) {
434
+ try {
435
+ val = JSON.parse(val);
436
+ }
437
+ catch (e) {
438
+ // Fallback to just returning the val as it might not be JSON
439
+ }
440
+ }
441
+ this._handleProviderResponse(JSON.stringify({
442
+ action: "RETRIEVE",
443
+ provider: "storage",
444
+ key: keyValue,
445
+ value: val
446
+ }));
447
+ }
448
+ break;
449
+ default:
450
+ throw new Error("Unsupported provider '" + msg.provider + "' and action '" + msg.action + "'");
451
+ }
452
+ break;
453
+ default:
454
+ // Just log that this provider is unsupported in a normal browser
455
+ console.error("Unsupported provider: " + msg.provider);
456
+ }
457
+ }
458
+ }
459
+ // This is called by native web view code
460
+ _handleProviderResponse(msg) {
461
+ if (!msg) {
462
+ return;
463
+ }
464
+ let msgJson = JSON.parse(msg);
465
+ let name = msgJson.provider;
466
+ let action = msgJson.action;
467
+ let deferredAndTimeout = this._pendingProviderPromises[name + action];
468
+ if (deferredAndTimeout) {
469
+ window.clearTimeout(deferredAndTimeout[1]);
470
+ delete this._pendingProviderPromises[name + action];
471
+ deferredAndTimeout[0].resolve(msgJson);
472
+ }
473
+ let listener = this._providerMessageListeners[name + action];
474
+ if (listener) {
475
+ listener(msgJson);
476
+ }
477
+ }
478
+ _callCompletedCallback() {
479
+ let callback = this._enableCompleteCallback;
480
+ this._enableCompleteCallback = null;
481
+ if (callback) {
482
+ window.setTimeout(() => {
483
+ callback();
484
+ }, 0);
485
+ }
486
+ }
487
+ static _createConsoleRegistration() {
488
+ let reg = {
489
+ name: platform.name,
490
+ version: platform.version,
491
+ platform: platform.os.toString(),
492
+ apps: [],
493
+ model: ((platform.manufacturer ? platform.manufacturer + " " : "") + (platform.product ? platform.product : "")).trim()
494
+ };
495
+ return reg;
496
+ }
497
+ _initialiseProvider(providerName) {
498
+ return __awaiter(this, void 0, void 0, function* () {
499
+ console.debug("Console: initialising provider '" + providerName + "'");
500
+ let initResponse;
501
+ try {
502
+ initResponse = (yield this.sendProviderMessage({
503
+ provider: providerName,
504
+ action: "PROVIDER_INIT"
505
+ }, true));
506
+ this._registration.providers[providerName].version = initResponse.version;
507
+ this._registration.providers[providerName].requiresPermission = initResponse.requiresPermission;
508
+ this._registration.providers[providerName].hasPermission = initResponse.hasPermission;
509
+ this._registration.providers[providerName].success = initResponse.success;
510
+ this._registration.providers[providerName].enabled = initResponse.enabled;
511
+ this._registration.providers[providerName].disabled = initResponse.disabled;
512
+ this._registration.providers[providerName].data = initResponse.data;
513
+ }
514
+ catch (e) {
515
+ console.error(e);
516
+ initResponse = {
517
+ action: "",
518
+ disabled: false,
519
+ enabled: false,
520
+ hasPermission: false,
521
+ provider: "",
522
+ requiresPermission: false,
523
+ version: "",
524
+ success: false
525
+ };
526
+ }
527
+ if (!initResponse.success) {
528
+ console.debug("Provider initialisation failed: '" + providerName + "'");
529
+ initResponse.disabled = true;
530
+ this._registration.providers[providerName].disabled = true;
531
+ }
532
+ if (initResponse.disabled || initResponse.enabled) {
533
+ let index = this._pendingProviderEnables.indexOf(providerName);
534
+ if (index >= 0) {
535
+ this._pendingProviderEnables.splice(index, 1);
536
+ }
537
+ }
538
+ });
539
+ }
540
+ }
541
+ //# sourceMappingURL=console.js.map
package/lib/defaults.js CHANGED
@@ -1 +1,16 @@
1
- export const DefaultColor4="#4d9d2a";export const DefaultColor7="#FFFFFF";export const DefaultColor1="#FFFFFF";export const DefaultColor2="#F9F9F9";export const DefaultColor5="#CCCCCC";export const DefaultColor6="#be0000";export const DefaultColor8="#FFFFFF";export const DefaultColor3="#4c4c4c";export const DefaultColor9="#000000";export const DefaultColor10="#000000";export const DefaultColor11="#FFFFFF";export const DefaultBoxShadowBottom="0 5px 5px -5px rgba(0,0,0,0.3)";export const DefaultBoxShadow="0 1px 3px 0 rgba(0,0,0,0.21)";export const DefaultHeaderHeight="50px";export const DefaultDisabledOpacity="0.3";
1
+ export const DefaultColor4 = "#4d9d2a"; // Primary
2
+ export const DefaultColor7 = "#FFFFFF"; // Secondary
3
+ export const DefaultColor1 = "#FFFFFF"; // Surface
4
+ export const DefaultColor2 = "#F9F9F9"; // Background
5
+ export const DefaultColor5 = "#CCCCCC"; // Borders and lines
6
+ export const DefaultColor6 = "#be0000"; // Invalid/Error
7
+ export const DefaultColor8 = "#FFFFFF"; // On Primary
8
+ export const DefaultColor3 = "#4c4c4c"; // Text / On Secondary
9
+ export const DefaultColor9 = "#000000"; // On Background
10
+ export const DefaultColor10 = "#000000"; // On Surface
11
+ export const DefaultColor11 = "#FFFFFF"; // On Error
12
+ export const DefaultBoxShadowBottom = "0 5px 5px -5px rgba(0,0,0,0.3)";
13
+ export const DefaultBoxShadow = "0 1px 3px 0 rgba(0,0,0,0.21)";
14
+ export const DefaultHeaderHeight = "50px";
15
+ export const DefaultDisabledOpacity = "0.3";
16
+ //# sourceMappingURL=defaults.js.map