-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathutils.js
714 lines (662 loc) · 24.6 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
import Soup from 'gi://Soup';
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
import Secret from 'gi://Secret';
import * as Settings from './settings.js';
let MyUUID = null; // "hass-gshell@geoph9-on-github";
let mscOptions = null;
let _settings = null;
let _metadata = null;
let _mainDir = null;
let _ = null;
let MessageTray = null;
let Main = null;
let TOKEN_SCHEMA;
export function init(
uuid,
settings,
metadata,
mainDir,
gettext_func,
messageTray_class=null, // not mandatory (only used for notifications in extensions.js)
main_class=null // not mandatory (only used for notifications in extensions.js)
) {
if (MyUUID === null) MyUUID = uuid;
if (_settings === null) _settings = settings;
if (_metadata === null) _metadata = metadata;
if (_mainDir === null) _mainDir = mainDir;
if (_ === null) _ = gettext_func;
if (mscOptions === null) mscOptions = new Settings.MscOptions(_metadata, _mainDir);
if (MessageTray === null && messageTray_class !== null) MessageTray = messageTray_class;
if (Main === null && main_class !== null) Main = main_class;
}
export function disable() {
if (mscOptions !== null) {
mscOptions.destroy();
mscOptions = null;
}
if (_settings !== null) _settings = null;
if (MyUUID !== null) MyUUID = null;
_settings = null;
}
export function getTokenSchema() {
if (!TOKEN_SCHEMA) {
TOKEN_SCHEMA = Secret.Schema.new(
"org.gnome.hass-data.Password",
/** DONT_MATCH_NAME is used as a workaround for a bug in gnome-keyring
* which prevents cold keyrings from being searched (and hence does not prompt for unlocking)
* see https://gitlab.gnome.org/GNOME/gnome-keyring/-/issues/89 and
* https://gitlab.gnome.org/GNOME/libsecret/-/issues/7 for more information
*/
Secret.SchemaFlags.DONT_MATCH_NAME,
{
"token_string": Secret.SchemaAttributeType.STRING,
}
);
}
return TOKEN_SCHEMA;
}
const VALID_TOGGLABLES = ['switch.', 'light.', 'fan.', 'input_boolean.', 'media_player.'];
const VALID_RUNNABLES = ['scene.', 'script.'];
/**
*
* @param {String} type Request type.
* @param {String} url Url of the request.
* @param {Object} data Data of the request (null if no data)
* @param {Function} callback The callback to run with resulting message
* @param {Function} on_error The callback to run on error (optional)
* @return {Soup.Message} A soup message with the requested parameters.
*/
function forge_async_message(type, url, data, callback, on_error=null) {
// Encode data to JSON (if provided)
if (data != null) data = JSON.stringify(data);
_log(
"Forge a %s message for %s (%s): firstly retrieve the API Long-Live Token...",
[type, url, data?"with data=%s".format(data):"without data"]
);
Secret.password_lookup(
getTokenSchema(),
{"token_string": "user_token"},
null,
(source, result) => {
let token = Secret.password_lookup_finish(result);
if (!token) {
_log(
"Fail to retreive API Long-Live Token from configuration, "
+ "can't construct API message", null, false
);
if (on_error) on_error();
return;
}
_log("API Long-Live Token retreived, forge message...");
// Initialize message and set the required headers
let message = Soup.Message.new(type, url);
message.request_headers.append('Authorization', `Bearer ${token}`);
message.request_headers.set_content_type("application/json", null);
if (data !== null){
let bytes2 = GLib.Bytes.new(data);
message.set_request_body_from_bytes('application/json', bytes2);
}
callback(message);
}
);
}
/**
*
* @param {String} url The url which you want to request
* @param {String} type Request type (e.g. 'GET', 'POST', default: GET)
* @param {Object} data Data that you want to send with the request (optional, must be in json format, default: null)
* @param {Function} callback The callback for request result (optional)
* @param {Function} on_error The callback to run on request error (optional)
* @return {Object} The response of the request (returns false if the request was unsuccessful)
*/
function send_async_request(url, type, data, callback=null, on_error=null) {
forge_async_message(
type ? type : 'GET',
url,
data,
(message) => {
// Initialize session
let session = Soup.Session.new();
session.set_timeout(5);
try {
_log("Sending %s request on %s...", [type, url]);
let result = session.send_and_read_async(
message,
GLib.PRIORITY_DEFAULT,
null,
(session, result) => {
_log(
"Handling result of %s request on %s (status: %s)...",
[type, url, Soup.Status.get_phrase(message.get_status())]
);
if (message.get_status() == Soup.Status.OK) {
result = session.send_and_read_finish(result);
if (!callback) {
_log("%s request on %s: success", [type, url]);
return;
}
try {
_log("Decoding result of %s request on %s...", [type, url]);
let decoder = new TextDecoder('utf-8');
let response = decoder.decode(result.get_data());
_log(
"Result of %s request on %s (%s): %s", [
type,
url,
data?"with data=%s".format(JSON.stringify(data)):"without data",
response
]);
_log("Run callback for %s request on %s", [type, url]);
callback(JSON.parse(response));
} catch (error) {
logError(error, `${MyUUID}: fail to decode result of request on ${url}.`);
if (on_error) on_error();
}
}
else {
_log(
"Invalid return of request on %s (status: %s)",
[url, Soup.Status.get_phrase(message.get_status())], false
);
if (on_error) on_error();
}
}
);
} catch (error) {
logError(error, `${MyUUID}: error durring request on ${url}: ${error}`);
if (on_error) on_error();
}
},
() => {
_log("Fail to build message for %s request on %s", [type, url]);
if (on_error) on_error();
return;
}
);
}
// Compute HASS URL
function computeURL(path, hass_url=null) {
let url = hass_url ? hass_url : mscOptions.hassUrl;
if (!RegExp('^https?://').exec(url))
url = `http://${url}` // use http:// by default
if (!path)
return url
if (!url.endsWith("/")) url += "/"; // needs a trailing slash
return url + path
}
/**
* Map an entity object
*
* @param {Object} entity The raw entity state object, as return by HASS API
* @returns {Object}
*/
function mapEntity(ent) {
return {
'entity_id': ent.entity_id,
'name': ent.attributes.friendly_name,
'attributes': ent.attributes,
'state': ent.state,
}
}
/**
* Get entities
*
* @param {Function} callback The callback to run with the result
* @param {Function} on_error The callback to run on error
* @param {Boolean} force_reload Force reloading cache (optional, default: false)
*
*/
export function getEntities(callback=null, on_error=null, force_reload=false) {
let entities = mscOptions.entitiesCache;
if (entities.length == 0 || force_reload) {
_log("get entities from API");
send_async_request(
computeURL('api/states'), 'GET', null,
function (response) {
if (Array.isArray(response)) {
let entities = response.map(mapEntity);
_log("%s entities retreived, sort it by name", [entities.length]);
entities = entities.sort((a,b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0));
_log("update entities cache");
mscOptions.entitiesCache = entities;
if (callback)
callback(entities);
}
else if (on_error) {
on_error();
}
}.bind(this),
on_error
);
}
else {
_log("get entities from cache");
if (callback) callback(entities);
}
}
/**
* Get one entity
*
* @param {String} entity_id The requested entity ID
* @param {Function} callback The callback to run with the result
* @param {Function} on_error The callback to run on error
* @param {Boolean} force_reload Force reloading cache (optional, default: false)
*
*/
function getEntity(entity_id, callback=null, on_error=null, force_reload=false) {
let entity = mscOptions.entitiesCache.filter(ent => ent.entity_id == entity_id);
if (entity.length == 0 || force_reload) {
_log("get entity %s from API", [entity_id]);
send_async_request(
computeURL(`api/states/${entity_id}`), 'GET', null,
function (response) {
if (typeof response === "object") {
if (callback)
callback(mapEntity(response));
}
else if (on_error) {
on_error();
}
}.bind(this),
on_error
);
}
else {
_log("get entity %s from cache", [entity_id]);
if (callback) callback(entity[0]);
}
}
/**
* Invalidate entities cache
*/
export function invalidateEntitiesCache() {
_log("invalidate entities cache");
mscOptions.entitiesCache = [];
}
/**
* Get entities by type
*
* @param {string} type The type of the entities to get ("runnable", "togglable", or "sensor") // TODO sensors!
* @param {Function} callback The callback to run with the result
* @param {Function} on_error The callback to run on error
* @param {Boolean} only_enabled Filter on enabled runnables (optional, default: false)
* @param {Boolean} force_reload Force reloading cache (optional, default: false)
*/
export function getEntitiesByType(type, callback, on_error=null, only_enabled=false, force_reload=false) {
getEntities(
function(entities) {
let results = [];
for (let ent of entities) {
if (only_enabled && !mscOptions.getEnabledByType(type).includes(ent.entity_id))
continue;
if (type === "sensor") {
if (!isSensor(ent))
continue;
results.push(mapSensor(ent));
} else {
let entitySupported = false;
if (type === "togglable") entitySupported = isEntitySupported(ent, VALID_TOGGLABLES)
else if (type === "runnable") entitySupported = isEntitySupported(ent, VALID_RUNNABLES)
if (entitySupported)
results.push({ 'entity_id': ent.entity_id, 'name': ent.name });
}
}
_log("%s entities found", [results.length]);
callback(results);
},
on_error,
force_reload
);
}
/**
* Map a sensor entity object
*
* @param {Object} entity The raw entity object, as returned by getEntity()/getEntities()
* @return {Object}
*/
function mapSensor(entity) {
return {
'entity_id': entity.entity_id,
'name': entity.name,
'unit': entity.attributes.unit_of_measurement,
'state': entity.state,
}
}
/**
* Check it's a sensor
*
* @param {Object} entity The entity object
* @return {Boolean}
*/
function isSensor(entity) {
return (
entity.entity_id.startsWith('sensor.')
&& entity.state
&& entity.attributes.unit_of_measurement
&& entity.state !== "unknown"
&& entity.state !== "unavailable"
);
}
/**
* Check if entity supported
*
* @param {Object} entity The entity object
* @param {Array} valid_domains Array of valid domain names
* @return {Boolean}
*/
function isEntitySupported(entity, valid_domains) {
// Not supported if not in valid domains:
if (valid_domains.filter(domain => entity.entity_id.startsWith(domain)).length == 0) return false
// Custom check for media players:
if (entity.entity_id.startsWith('media_player.')) {
/** Check if media_player supports toggle service.
* It can be read from the supported_features attribute, TURN_OFF and TURN_ON features have to be supported
* Decimal values for these features are 128 and 256 respectively:
* https://github.com/home-assistant/core/blob/dev/homeassistant/components/media_player/const.py
*
* To check, supported_features have to be converted to binary,
* than check if the 8th and 9th position from the right is 1.
*/
if (!entity.attributes.supported_features) return false
// Convert supported_features to binary:
let supported_features_bin = parseInt(entity.attributes.supported_features).toString(2)
return (
// Check if enough digits:
supported_features_bin.length > 8
// 8th digit from the right is TURN_ON:
&& supported_features_bin.charAt(supported_features_bin.length - 8) === '1'
// 9th digit from the right is TURN_OFF:
&& supported_features_bin.charAt(supported_features_bin.length - 9) === '1'
);
} else {
return true
}
}
/**
* Get sensors
*
* @param {Function} callback The callback to run with the result
* @param {Function} on_error The callback to run on error
* @param {Boolean} only_enabled Filter on enabled togglables (optional, default: false)
* @param {Boolean} force_reload Force reloading cache (optional, default: false)
*
*/
export function getSensors(callback, on_error=null, only_enabled=false, force_reload=false) {
getEntities(
function(entities) {
let sensors = [];
for (let ent of entities) {
if (only_enabled && !mscOptions.enabledSensors.includes(ent.entity_id))
continue;
if (!isSensor(ent))
continue;
sensors.push(mapSensor(ent));
}
_log("%s %ssensor entities found", [sensors.length, only_enabled?'enabled ':'']);
callback(sensors);
},
on_error,
force_reload
);
}
/**
* Get a sensor by its id
*
* @param {String} sensor_id The expected sensor ID
* @param {Function} callback The callback to run with the result
* @param {Function} on_not_found The callback to run if sensor is not found (or on error)
* @param {Boolean} force_reload Force reloading cache (optional, default: false)
*
*/
export function getSensor(sensor_id, callback, on_not_found=null, force_reload=false) {
getEntity(
sensor_id,
function(entity) {
if (isSensor(entity)) {
callback(mapSensor(entity));
return;
}
_log('getSensor(%s): is not a sensor (%s)', [sensor_id, JSON.stringify(entity)]);
if (on_not_found) on_not_found();
},
on_not_found,
force_reload
);
}
/**
* Toggle an entity in Home-Assistant
* @param {String} entityId The entity ID
*/
export function toggleEntity(entity) {
let data = { "entity_id": entity.entity_id };
let domain = entity.entity_id.split(".")[0]; // e.g. light.mylight => light
send_async_request(
computeURL(`api/services/${domain}/toggle`),
'POST',
data,
function(response) {
_log(
'HA result toggling %s (%s): %s',
[entity.name, entity.entity_id, JSON.stringify(response)]
);
// HA do not return new entity state in each case and not only the one we requested
let state = null;
for (let ent of response) {
if (ent.entity_id == entity.entity_id) {
state = ent.state;
break;
}
}
if (state == 'on')
notify(
_('%s toggled on').format(entity.name),
_('%s successfully toggled on.').format(entity.name)
);
else if (state == 'off')
notify(
_('%s toggled off').format(entity.name),
_('%s successfully toggled off.').format(entity.name)
);
else
notify(
_('%s toggled').format(entity.name),
_('%s successfully toggled.').format(entity.name)
);
},
function() {
notify(
_('Error toggling %s').format(entity.name),
_('Error occured trying to toggle %s.').format(entity.name),
)
}
);
}
/**
* Turns an entity on in Home-Assistant
* @param {String} entityId The entity ID
*/
export function turnOnEntity(entity) {
let data = { "entity_id": entity.entity_id };
let domain = entity.entity_id.split(".")[0]; // e.g. script.run_me => script
send_async_request(
computeURL(`api/services/${domain}/turn_on`),
'POST',
data,
function(response) {
_log(
'HA result turning on %s (%s): %s',
[entity.name, entity.entity_id, JSON.stringify(response)]
);
// HA does respond with a timestamp as a new scenes/scripts state,
// so there is no use in computing the response here
},
function() {
notify(
_('Error turning on %s').format(entity.name),
_('Error occured trying to turn on %s.').format(entity.name),
)
}
);
}
/**
* Trigger Home-Assistant event by name
* @param {String} eventName The HA event name (start/stop/restart)
*/
export function triggerHassEvent(eventName, callback=null, on_error=null) {
send_async_request(
computeURL(`api/events/homeassistant_${eventName}`),
'POST',
null,
function() {
if (eventName == 'start')
notify(
_('Home-Assistant start event triggered'),
_('Home-Assistant start event successfully triggered.')
);
else if (eventName == 'stop')
notify(
_('Home-Assistant stop event triggered'),
_('Home-Assistant stop event successfully triggered.')
);
else if (eventName == 'close')
notify(
_('Home-Assistant close event triggered'),
_('Home-Assistant close event successfully triggered.')
);
else
notify(
_('Home-Assistant event triggered'),
_('Home-Assistant event successfully triggered.')
);
},
function() {
if (eventName == 'start')
notify(
_('Error triggering Home-Assistant start event'),
_('Error occured triggering Home-Assistant start event.'),
);
else if (eventName == 'stop')
notify(
_('Error triggering Home-Assistant stop event'),
_('Error occured triggering Home-Assistant stop event.'),
);
else if (eventName == 'close')
notify(
_('Error triggering Home-Assistant close event'),
_('Error occured triggering Home-Assistant close event.'),
);
else
notify(
_('Error triggering Home-Assistant event'),
_('Error occured triggering Home-Assistant event.'),
);
}
);
}
/**
* Check equality of elements of two arrays
* @param {Array} a Array 1
* @param {Array} b Array 2
* @return {Boolean} true if the two arrays have the same elements. false otherwise.
*/
export function arraysEqual(a, b) {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length !== b.length) return false;
// If you don't care about the order of the elements inside
// the array, you should sort both arrays here.
// Please note that calling sort on an array will modify that array.
// you might want to clone your array first.
for (let i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
// const getMethods = (obj) => {
// let properties = new Set()
// let currentObj = obj
// do {
// Object.getOwnPropertyNames(currentObj).map(item => properties.add(item))
// } while ((currentObj = Object.getPrototypeOf(currentObj)))
// return [...properties.keys()].filter(item => typeof obj[item] === 'function')
// }
export function getEntityIcon(domain) {
let icon_path = _mainDir.get_path();
switch (domain) {
case "scene":
icon_path += '/icons/palette.svg';
break;
case "script":
icon_path += '/icons/script-text.svg';
break;
case "light":
icon_path += '/icons/ceiling-light.svg';
break;
case "fan":
icon_path += '/icons/fan.svg';
break;
case "media_player":
icon_path += '/icons/media-player.svg';
break;
case "switch":
case "input_boolean":
icon_path += '/icons/toggle-switch-outline.svg';
break;
default:
// no need for a default as these are all the supported domains by the plugin, but log anyways
_log(`Received unexpected domain in getEntityIcon: ${domain}`)
}
return Gio.icon_new_for_string(icon_path);
}
/**
* Log a message
* @param {String} msg The message
* @param {[Mixed]} [args=null] If array provided, it will be used to format the mesage
* using it format() method (optional, default: null)
* @param {Boolean} [debug=true] If true, consider message as debugging one and logged it
* only if the debug mode is enabled (optional, default: true)
*/
export function _log(msg, args=null, debug=true) {
if (debug && !mscOptions.debugMode) return;
if (args) msg = msg.format.apply(msg, args);
log(`${MyUUID}: ${msg}`);
}
export function notify(msg, details) {
if (!mscOptions.showNotifications) return;
// let Main = imports.ui.main;
// let MessageTray = imports.ui.messageTray;
let source = new MessageTray.Source(_metadata.name);
Main.messageTray.add(source);
let notification = new MessageTray.Notification(
source, msg, details,
{gicon: Gio.icon_new_for_string(_mainDir.get_path() + '/icons/hass-symbolic.svg')}
);
notification.setTransient(true);
source.showNotification(notification);
}
/**
* Connect specified settings changes to provided callback
* @param {Array} settings List of settings
* @param {Function} callback The callback to run on change
* @param {Array} [args=[]] Optional arguments to pass to callback
*/
export function connectSettings(settings, callback, args=[]) {
let connectedSettingIds = [];
for (let setting of settings) {
connectedSettingIds.push(
_settings.connect(
"changed::" + setting,
() => callback.apply(this, args)
)
);
}
return connectedSettingIds;
}
/**
* Disconnect connected settings by ID
* @param {Array} connectedSettingIds List of connected setting IDs
*/
export function disconnectSettings(connectedSettingIds) {
connectedSettingIds.forEach(id => _settings.disconnect(id));
}