-
Notifications
You must be signed in to change notification settings - Fork 12
/
app.js
430 lines (351 loc) · 12.4 KB
/
app.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
'use strict';
const fs = require('fs').promises;
const vm = require('vm');
const util = require('util');
const path = require('path');
const http = require('http');
const https = require('https');
const uuid = require('uuid');
const Homey = require('homey');
const { HomeyAPI: HomeyAPILegacy } = require('athom-api');
const { HomeyAPIV2, HomeyAPIV3Local } = require('homey-api');
const fetch = require('node-fetch');
const _ = require('lodash');
const { RunCondition } = require('./lib/flow/conditions/RunCondition');
const { RunWithArgCondition } = require('./lib/flow/conditions/RunWithArgCondition');
const { RunCodeCondition } = require('./lib/flow/conditions/RunCodeCondition');
const { RunCodeWithArgCondition } = require('./lib/flow/conditions/RunCodeWithArgCondition');
const { RunAction } = require('./lib/flow/actions/RunAction');
const { RunCodeAction } = require('./lib/flow/actions/RunCodeAction');
const { RunWithArgAction } = require('./lib/flow/actions/RunWithArgAction');
const { RunCodeReturnsStringAction } = require('./lib/flow/actions/RunCodeReturnsStringAction');
const { RunCodeReturnsNumberAction } = require('./lib/flow/actions/RunCodeReturnsNumberAction');
const { RunCodeReturnsBooleanAction } = require('./lib/flow/actions/RunCodeReturnsBooleanAction');
const { RunCodeWithArgAction } = require('./lib/flow/actions/RunCodeWithArgAction');
const { RunCodeWithArgReturnsStringAction } = require('./lib/flow/actions/RunCodeWithArgReturnsStringAction');
const { RunCodeWithArgReturnsNumberAction } = require('./lib/flow/actions/RunCodeWithArgReturnsNumberAction');
const { RunCodeWithArgReturnsBooleanAction } = require('./lib/flow/actions/RunCodeWithArgReturnsBooleanAction');
module.exports = class HomeyScriptApp extends Homey.App {
static RUN_TIMEOUT = 1000 * 30; // 30s
async onInit() {
// Remove since alot of them will be caused by user errors.
process.removeAllListeners('unhandledRejection');
process.on('unhandledRejection', (reason, promise) => {
this.error('Unhandled Rejection:', reason);
});
// Init Scripts
this.scripts = this.homey.settings.get('scripts');
this.localUrl = await this.homey.api.getLocalUrl();
this.sessionToken = await this.homey.api.getOwnerApiToken();
this.apiProps = await (async () => {
const props = {
token: this.sessionToken,
baseUrl: this.localUrl,
strategy: [],
properties: {
id: await this.homey.cloud.getHomeyId(),
softwareVersion: this.homey.version,
},
};
return props;
})();
const exampleFolder = this.homey.platformVersion >= 2 ? 'examples' : 'examples-v1';
if (!this.scripts) {
this.log('No scripts found.');
const scripts = {};
// Copy example scripts
try {
const files = await fs.readdir(path.join(__dirname, exampleFolder));
await Promise.all(files.map(async filename => {
if (!filename.endsWith('.js')) return;
const id = `example-${filename.substring(0, filename.length - '.js'.length)}`;
const filepath = path.join(__dirname, exampleFolder, filename);
const code = await fs.readFile(filepath, 'utf8');
scripts[id] = {
code,
lastExecuted: null,
version: 2,
};
this.log(`Found Example: ${id}`);
}));
} catch (err) {
this.error('Examples Error:', err);
}
// Check for existing (SDK2) scripts in /userdata
try {
const files = await fs.readdir(path.join(__dirname, 'userdata', 'scripts'));
await Promise.all(files.map(async filename => {
if (!filename.endsWith('.js')) return;
const id = filename.substring(0, filename.length - '.js'.length);
const filepath = path.join(__dirname, 'userdata', 'scripts', filename);
const code = await fs.readFile(filepath, 'utf8');
scripts[id] = {
code,
lastExecuted: new Date(this.homey.settings.get(`last-execution-${id}`)),
};
this.log(`Found Migration: ${id}`);
}));
} catch (err) {
this.error('Migration Error:', err);
}
this.scripts = scripts;
this.homey.settings.set('scripts', this.scripts);
}
// Migration
if (this.scripts) {
const scriptEntries = Object.entries(this.scripts);
let anyScriptChanged = false;
for (const [scriptId, script] of scriptEntries) {
if (typeof script.name !== 'string') {
anyScriptChanged = true;
script.name = scriptId;
script.id = scriptId;
}
if (typeof script.version !== 'number') {
anyScriptChanged = true;
script.version = 1;
}
}
if (anyScriptChanged) {
this.homey.settings.set('scripts', this.scripts);
}
}
// Register Flow Cards
this.runCondition = new RunCondition({ homey: this.homey });
this.runWithArgCondition = new RunWithArgCondition({ homey: this.homey });
this.runCodeCondition = new RunCodeCondition({ homey: this.homey });
this.runCodeWithArgCondition = new RunCodeWithArgCondition({ homey: this.homey });
this.runAction = new RunAction({ homey: this.homey });
this.runWithArgAction = new RunWithArgAction({ homey: this.homey });
this.runCodeAction = new RunCodeAction({ homey: this.homey });
this.runCodeReturnsStringAction = new RunCodeReturnsStringAction({ homey: this.homey });
this.runCodeReturnsNumberAction = new RunCodeReturnsNumberAction({ homey: this.homey });
this.runCodeReturnsBooleanAction = new RunCodeReturnsBooleanAction({ homey: this.homey });
this.runCodeWithArgAction = new RunCodeWithArgAction({ homey: this.homey });
this.runCodeWithArgReturnsStringAction = new RunCodeWithArgReturnsStringAction({ homey: this.homey });
this.runCodeWithArgReturnsNumberAction = new RunCodeWithArgReturnsNumberAction({ homey: this.homey });
this.runCodeWithArgReturnsBooleanAction = new RunCodeWithArgReturnsBooleanAction({ homey: this.homey });
// Register Flow Tokens
this.tokens = this.homey.settings.get('tokens') || {};
this.tokensInstances = {};
await Promise.all(Object.keys(this.tokens).map(async id => {
this.tokensInstances[id] = await this.homey.flow.createToken(id, {
title: id,
type: this.tokens[id].type,
value: this.tokens[id].value,
});
})).catch(this.error);
}
createAppApi() {
if (this.homey.platform === 'local' && this.homey.platformVersion === 1) {
return new HomeyAPIV2(this.apiProps);
}
if (this.homey.platform === 'local' && this.homey.platformVersion >= 2) {
return new HomeyAPIV3Local(this.apiProps);
}
throw new Error('Not Supported');
}
getHomeyAPI({ version }) {
if (version >= 2) {
const api = this.createAppApi();
return api;
}
const api = new HomeyAPILegacy({
localUrl: this.localUrl,
baseUrl: this.localUrl,
token: this.sessionToken,
apiVersion: 2,
online: true,
}, () => {
// called by HomeyAPI on 401 requests
api.setToken(this.sessionToken);
});
return api;
}
async onFlowGetScriptAutocomplete(query) {
const scripts = await this.getScripts();
return Object.values(scripts)
.filter(script => script.name.toLowerCase().includes(query.toLowerCase()))
.map(script => ({
id: script.id,
name: script.name,
}));
}
async setToken({ id, value, type = typeof value }) {
// Delete the Token
if (typeof value === 'undefined' || value === null) {
if (this.tokensInstances[id]) {
await this.tokensInstances[id].unregister().catch(this.error);
}
if (this.tokens[id]) {
delete this.tokens[id];
delete this.tokensInstances[id];
this.homey.settings.set('tokens', this.tokens);
}
return;
}
// Create the Token
if (!this.tokensInstances[id]) {
this.tokensInstances[id] = await this.homey.flow.createToken(id, {
type,
value,
title: id,
});
this.tokens[id] = { type, value };
this.homey.settings.set('tokens', this.tokens);
return;
}
// Update the Token
if (this.tokensInstances[id]) {
await this.tokensInstances[id].setValue(value);
this.tokens[id].value = value;
this.homey.settings.set('tokens', this.tokens);
}
}
async getScripts() {
return this.scripts;
}
async getScript({ id }) {
const script = this.scripts[id];
if (!script) {
throw new Error('Script Not Found');
}
return {
...script,
lastExecuted: new Date(script.lastExecuted),
};
}
async runScript({
id,
name,
code,
lastExecuted,
args = [],
version,
realtime = true,
}) {
if (lastExecuted == null) lastExecuted = new Date();
const homeyAPI = this.getHomeyAPI({ version });
// Create a Logger
const log = (...props) => {
this.log(`[${name}]`, ...props);
if (realtime) {
this.homey.api.realtime('log', {
text: util.format(...props),
script: id,
});
}
};
// Create the Context
const context = vm.createContext({
args,
// 3rd party modules
_,
fetch,
http,
https,
URLSearchParams,
Buffer,
// System
__filename__: `${name}.js`,
__script_id__: id,
__last_executed__: lastExecuted,
__ms_since_last_executed__: Date.now() - lastExecuted.getTime(),
// Homey API
Homey: homeyAPI,
// Logging
log,
console: {
log,
error: log,
info: log,
},
// Shortcuts
say: async text => homeyAPI.speechOutput.say({ text }),
tag: async (id, value) => this.setToken({ id, value }),
wait: async delay => new Promise(resolve => setTimeout(resolve, delay)),
// Cross-Script Settings
global: {
get: key => this.homey.settings.get(`homeyscript-${key}`),
set: (key, value) => this.homey.settings.set(`homeyscript-${key}`, value),
keys: () => this.homey.settings.getKeys()
.filter(key => key.startsWith('homeyscript-'))
.map(key => key.substring('homeyscript-'.length)),
},
// Deprecated
setTagValue: async (id, opts, value) => {
log('Warning: setTagValue(id, opts, value) is deprecated, please use tag(id, value)');
await this.setToken({
id,
value,
type: opts.type,
});
},
});
try {
// Create the Sandbox
const sandbox = new vm.Script(`Promise.resolve().then(async () => {\n${code}\n});`, {
filename: `${name}.js`,
lineOffset: -1,
columnOffset: 0,
});
const runPromise = sandbox.runInNewContext(context, {
displayErrors: true,
timeout: this.constructor.RUN_TIMEOUT,
microtaskMode: 'afterEvaluate', // from Node 14 should properly timeout async script
});
const result = await runPromise;
log('\n———————————————————\n✅ Script Success\n');
log('↩️ Returned:', JSON.stringify(result, false, 2));
return result;
} catch (err) {
log('\n———————————————————\n❌ Script Error\n');
log('⚠️', err.stack);
// Create a new Error because an Error from the sandbox behaves differently
const error = new Error(err.message);
error.stack = err.stack;
throw error;
} finally {
if (homeyAPI) {
homeyAPI.destroy();
}
}
}
async createScript({ name, code }) {
const newScript = {
id: uuid.v4(),
name,
code,
version: 2,
lastExecuted: null,
};
this.scripts[newScript.id] = newScript;
this.homey.settings.set('scripts', this.scripts);
return newScript;
}
async updateScript({
id, name, code, lastExecuted, version,
}) {
this.scripts[id] = {
...this.scripts[id],
};
if (name != null) {
this.scripts[id].name = name;
}
if (code != null) {
this.scripts[id].code = code;
}
if (lastExecuted != null) {
this.scripts[id].lastExecuted = lastExecuted;
}
if (version != null) {
this.scripts[id].version = version;
}
this.homey.settings.set('scripts', this.scripts);
return this.scripts[id];
}
async deleteScript({ id }) {
delete this.scripts[id];
this.homey.settings.set('scripts', this.scripts);
}
};