forked from csuermann/node-red-contrib-virtual-smart-home
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.html
689 lines (602 loc) · 18.3 KB
/
connection.html
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
<script type="text/javascript">
;(function () {
let pollingIntervalId
let registeredDeviceCount = 0
async function execPostRequest(url, data = {}) {
return (
await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
body: JSON.stringify(data),
})
).json()
}
async function execGetRequest(url, headers = {}) {
return (
await fetch(url, {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
...headers,
},
redirect: 'follow',
})
).json()
}
async function getInstalledVshVersion() {
const response = await fetch(
'./icons/node-red-contrib-virtual-smart-home/version.txt',
{
method: 'GET',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
}
)
return (await response.text()).trim()
}
async function execDeleteRequest(url, headers = {}, data = {}) {
return (
await fetch(url, {
method: 'DELETE',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
...headers,
'Content-Type': 'application/json',
},
redirect: 'follow',
body: JSON.stringify(data),
})
).json()
}
function fetchDeviceCode() {
const url = 'https://api.amazon.com/auth/o2/create/codepair'
const data = {
response_type: 'device_code',
client_id:
'amzn1.application-oa2-client.3f1bb07133854b078261ad43f2484c18',
scope: 'profile',
}
return execPostRequest(url, data)
}
async function ensureValidAccessToken() {
const now = new Date().getTime()
const expiry = $('#node-config-input-accessTokenExpiry').val() || 0
const refreshToken = $('#node-config-input-refreshToken').val()
if (expiry < now) {
try {
const tokenData = await fetchFreshAccessToken(refreshToken)
populateTokenData(tokenData)
} catch (e) {
showError('fetching a fresh Access Token failed')
}
}
return $('#node-config-input-accessToken').val()
}
async function fetchFreshAccessToken(refreshToken) {
const url = 'https://api.amazon.com/auth/o2/token'
const data = {
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id:
'amzn1.application-oa2-client.3f1bb07133854b078261ad43f2484c18',
}
const resp = await execPostRequest(url, data)
if (!resp.access_token) {
throw new Error('could not fetch access token')
} else {
return resp
}
}
async function fetchDeviceToken(device_code, user_code) {
const url = 'https://api.amazon.com/auth/o2/token'
const data = {
grant_type: 'device_code',
device_code,
user_code,
}
const resp = await execPostRequest(url, data)
if (resp.error && resp.error == 'authorization_pending') {
const err = new Error('authorization_pending')
err.status = 400
throw err
} else {
return resp
}
}
function populateTokenData({ access_token, refresh_token, expires_in }) {
$('#node-config-input-refreshToken').val(refresh_token)
$('#node-config-input-accessToken').val(access_token)
const accessTokenExpiryTimestamp =
new Date().getTime() + (expires_in - 15) * 1000
$('#node-config-input-accessTokenExpiry').val(accessTokenExpiryTimestamp)
}
function provisionDevice(accessToken, installedVshVersion) {
return execPostRequest(
'https://kfd5m4a21f.execute-api.eu-west-1.amazonaws.com/dev/provision',
{
accessToken: accessToken,
vshVersion: installedVshVersion,
}
)
}
function getRegisteredDevices(accessToken) {
return execGetRequest(
'https://kfd5m4a21f.execute-api.eu-west-1.amazonaws.com/dev/devices',
{ Authorization: accessToken }
)
}
function checkVersion(version) {
return execGetRequest(
`https://kfd5m4a21f.execute-api.eu-west-1.amazonaws.com/dev/check_version?version=${version}`
)
}
function stopPolling() {
if (pollingIntervalId) {
clearInterval(pollingIntervalId)
}
}
function showError(errorMsg) {
$('#error-msg').html(errorMsg)
$('#error').show()
}
async function deleteDevice(thingId, deviceId) {
$(`#${deviceId}`).fadeOut()
registeredDeviceCount--
if (registeredDeviceCount == 0) {
$('#empty').show()
$('#device-list-table').hide()
}
const accessToken = await ensureValidAccessToken()
const deleteResult = await execDeleteRequest(
'https://kfd5m4a21f.execute-api.eu-west-1.amazonaws.com/dev/device',
{ Authorization: accessToken },
{ thingId, deviceId }
)
if (deleteResult.error) {
showError('delete failed')
$(`#${deviceId}`).fadeIn()
}
}
async function displayRegisteredDevices() {
$('#registered-devices').show()
const accessToken = await ensureValidAccessToken()
let registeredDevices = await getRegisteredDevices(accessToken)
registeredDeviceCount = registeredDevices.length
$('#loading').hide()
if (registeredDevices.length == 0) {
$('#empty').show()
return
}
registeredDevices = registeredDevices.sort((a, b) => {
const nameA = a.friendlyName.toUpperCase()
const nameB = b.friendlyName.toUpperCase()
let comparison = 0
if (nameA > nameB) {
comparison = 1
} else if (nameA < nameB) {
comparison = -1
}
return comparison
})
registeredDevices = registeredDevices.map((item) => {
var splitStr = item.template.toLowerCase().split('_')
for (var i = 0; i < splitStr.length; i++) {
splitStr[i] =
splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1)
}
item.template = splitStr.join(' ')
return item
})
$.each(registeredDevices, function (i, item) {
let $tr = $('<tr>')
.attr('id', item.deviceId)
.addClass(
item.thingId == $('#node-config-input-thingId').val()
? 'same-thing'
: 'other-thing'
)
.append(
$('<td>').text(item.friendlyName),
$('<td>').text(item.template),
$('<td>')
.addClass('action-column')
.append(
$('<i class="fa fa-trash">').on('click', () =>
deleteDevice(item.thingId, item.deviceId)
)
)
)
.appendTo('#device-list-table')
})
$('#device-list-table').show()
}
async function oneditprepare() {
if (!this.credentials.email) {
const installedVshVersion = await getInstalledVshVersion()
const versionCheckResult = await checkVersion(installedVshVersion)
if (!versionCheckResult.isAllowedVersion) {
return showError(versionCheckResult.updateHint)
}
try {
const {
device_code,
expires_in,
interval,
user_code,
verification_uri,
} = await fetchDeviceCode()
const now = new Date()
const expiresAt = new Date(now.getTime() + expires_in * 1000)
$('#user-code').html(user_code)
$('#verification-uri').attr('href', verification_uri)
$('#verification-uri').html(verification_uri)
$('#refresh-interval').html(interval)
pollingIntervalId = setInterval(async () => {
if (new Date() > expiresAt) {
stopPolling()
$('#device-code').hide()
return showError('code expired')
}
try {
console.log('polling for deviceTokenResponse...')
const deviceTokenResponse = await fetchDeviceToken(
device_code,
user_code
)
stopPolling()
console.log('deviceTokenResponse', deviceTokenResponse)
const provisionData = await provisionDevice(
deviceTokenResponse.access_token,
installedVshVersion
)
if (provisionData.error) {
const error = new Error(provisionData.error)
error.status = 500 //so that catch below works!
throw error
}
$('#device-code').hide()
populateTokenData(deviceTokenResponse)
$('#node-config-input-name').val(provisionData.email)
$('#node-config-input-email').val(provisionData.email)
$('#node-config-input-server').val(provisionData.server)
$('#node-config-input-port').val(provisionData.port)
$('#node-config-input-cert').val(provisionData.cert)
$('#node-config-input-privateKey').val(provisionData.privateKey)
$('#node-config-input-caCert').val(provisionData.caCert)
$('#node-config-input-thingId').val(provisionData.thingId)
$('#provisioned').show()
console.log('provisionData', provisionData)
} catch (e) {
if (e.status != 400) {
stopPolling()
$('#device-code').hide()
console.log(e)
showError(e.message)
}
}
}, interval * (1000 / 2)) //twice as fast as allowed...
$('#device-code').show()
} catch (e) {
alert(e)
}
} else {
$('#provisioned').show()
displayRegisteredDevices()
}
}
function oneditsave() {
stopPolling()
}
RED.nodes.registerType('vsh-connection', {
category: 'config',
paletteLabel: 'connection',
defaults: {
name: { value: '' },
port: { value: '', required: true },
accessTokenExpiry: { value: 0 },
},
credentials: {
refreshToken: { type: 'text' },
accessToken: { type: 'text' },
email: { type: 'text' },
cert: { type: 'text' },
privateKey: { type: 'text' },
caCert: { type: 'text' },
thingId: { type: 'text' },
server: { type: 'text', required: true },
},
label: function () {
return this.name || `connection_${this.id}`
},
paletteLabel: 'connection',
oneditprepare,
oneditsave,
oneditcancel: stopPolling,
})
})()
</script>
<style>
#provisioned,
#registered-devices,
#device-list-table,
#device-code,
#empty,
#error {
display: none;
}
.hidden {
display: none;
}
#device-code,
#error {
padding: 10px;
text-align: center;
border: 3px red dashed;
}
#provisioned h1,
#registered-devices h1 {
font-size: 1.5em;
margin-top: 30px;
}
#registered-devices table {
border-collapse: collapse;
width: 100%;
}
#registered-devices table,
#registered-devices th,
#registered-devices td {
border: 1px solid black;
padding: 5px;
text-align: left;
}
#registered-devices td.action-column {
text-align: center;
}
#registered-devices td.action-column i {
cursor: pointer;
}
#registered-devices .other-thing {
background-color: #f5f2f2;
}
#user-code {
font-family: 'Courier New', Courier, monospace;
font-size: 140%;
font-weight: bold;
color: #3737bd;
}
#device-code a {
text-decoration: underline !important;
}
#device-code .step {
height: 25px;
width: 25px;
line-height: 25px;
color: rgb(236, 233, 233);
background-color: rgb(114, 137, 160);
border-radius: 50%;
display: inline-block;
}
</style>
<script type="text/html" data-template-name="vsh-connection">
<div class="form-row">
<label for="node-config-input-name"><i class="fa fa-tag"></i> Name</label>
<input type="text" id="node-config-input-name" placeholder="Name" />
</div>
<div id="error">
<h1>ERROR</h1>
<span id="error-msg">ERROR-MSG</span>
</div>
<div id="device-code">
<h1>Account Linking</h1>
<p style="color:darkorange; font-weight:bold;">
If you already created a connection for your Amazon account, please reuse
that connection instead of creating another one!
</p>
<p>
Follow these steps to link this connection to the <i>same</i> Amazon Alexa
account that was used to activate the 'virtual smart home' skill.
</p>
<p>
<span class="step">1</span>
<br />
Go to
<a id="verification-uri" href="" target="_blank">VERIFICATION_URI</a>
</p>
<p>
<span class="step">2</span>
<br />
Enter this code (after logging in)
<br />
<span id="user-code">USER_CODE</span>
</p>
<p>
<span class="step">3</span>
<br />
Wait for your account details to appear here (<<span
id="refresh-interval"
>REFRESH-INTERVAL</span
>
sec)
</p>
<p>
<span class="step">4</span>
<br />
Close this dialog by clicking the "Add" / "Update"
button
</p>
</div>
<div id="provisioned">
<h1>Connection Details</h1>
<div class="form-row">
<label for="node-config-input-email"
><i class="fa fa-amazon"></i> Account</label
>
<input
type="text"
id="node-config-input-email"
readonly
placeholder="Email"
/>
</div>
<div class="form-row hidden">
<label for="node-config-input-accessToken"
><i class="fa fa-ticket"></i> Access Token</label
>
<input
type="text"
id="node-config-input-accessToken"
readonly
placeholder="Access Token"
/>
</div>
<div class="form-row hidden">
<label for="node-config-input-accessTokenExpiry"
><i class="fa fa-clock-o"></i> Token Expiry</label
>
<input
type="text"
id="node-config-input-accessTokenExpiry"
readonly
placeholder="Access Token Expiry"
/>
</div>
<div class="form-row hidden">
<label for="node-config-input-refreshToken"
><i class="fa fa-refresh"></i> Refresh Token</label
>
<input
type="text"
id="node-config-input-refreshToken"
readonly
placeholder="Refresh Token"
/>
</div>
<div class="form-row hidden">
<label for="node-config-input-server"
><i class="fa fa-server"></i> Server</label
>
<input
type="text"
id="node-config-input-server"
readonly
placeholder="Server"
/>
</div>
<div class="form-row hidden">
<label for="node-config-input-port"
><i class="fa fa-building"></i> Port</label
>
<input
type="text"
id="node-config-input-port"
readonly
placeholder="Port"
/>
</div>
<div class="form-row hidden">
<label for="node-config-input-cert"
><i class="fa fa-certificate"></i> Certificate</label
>
<input
type="text"
id="node-config-input-cert"
readonly
placeholder="Certificate"
/>
</div>
<div class="form-row hidden">
<label for="node-config-input-privateKey"
><i class="fa fa-key"></i> Private Key</label
>
<input
type="text"
id="node-config-input-privateKey"
readonly
placeholder="Private Key"
/>
</div>
<div class="form-row hidden">
<label for="node-config-input-caCert"
><i class="fa fa-certificate"></i> CA Certificate</label
>
<input
type="text"
id="node-config-input-caCert"
readonly
placeholder="CA Certificate"
/>
</div>
<div class="form-row">
<label for="node-config-input-thingId"
><i class="fa fa-cog"></i> Thing ID</label
>
<input
type="text"
id="node-config-input-thingId"
readonly
placeholder="Thing ID"
/>
</div>
</div>
<div id="registered-devices">
<h1>Registered Devices</h1>
<div id="loading">...loading...</div>
<div id="empty">
There are currently no devices registered for this account
</div>
<div>
<table id="device-list-table">
<tr>
<th style="width: 45%">Name</th>
<th style="width: 45%">Type</th>
<th> </th>
</tr>
</table>
</div>
</div>
</script>
<script type="text/html" data-help-name="vsh-connection">
<p>A connection to the IoT cloud, linked to an Alexa account.</p>
<p>
<strong>Note:</strong> Although it is possible to create multiple
connections that are all linked to the same Alexa account, this comes with
an overhead and should be avoided. For most use-cases one single connection
that is shared by many virtual devices should suffice.
</p>
<h3>Account Linking</h3>
<p>
The connection must be linked to the same Amazon Alexa account that was /
will be used to activate the 'virtual smart home' skill. To achieve that, a
temporary code will be displayed that needs to be entered at
https://amazon.com/us/code.
</p>
<h3>Connection Details</h3>
<p>
Once account linking is completed, the connection details will be displayed.
They will however only be needed for troubleshooting support requests.
</p>
<h3>Registered Devices</h3>
<p>
The 'Registered Devices' section lists all virtual devices that are
associated with the Alexa account the connection was linked with. Hence the
list might contain more devices than the ones using this connection. Devices
linked to another connection are displayed with a gray background.
</p>
<p>
Registered devices can be deleted by clicking the trash icon, which will
also delete the device from Alexa. Note that a deleted device might
re-appear if its corresponding vsh-virtual-device node still exists and
reconnects.
</p>
</script>