UNPKG

node-red-contrib-virtual-smart-home

Version:

A Node-RED node that represents a 'virtual device' which can be controlled via Alexa. Requires the virtual smart home skill to be enabled for your Amazon account.

957 lines (833 loc) 26.4 kB
<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 getBackendUrl() { return ( $('#node-config-input-backendUrl').val() || RED.settings.vshConnectionDefaultBackendUrl ) } function getLwaClientId() { return ( $('#node-config-input-lwaClientId').val() || RED.settings.vshConnectionDefaultLwaClientId ) } function fetchDeviceCode() { const url = 'https://api.amazon.com/auth/o2/create/codepair' const data = { response_type: 'device_code', client_id: $('#node-config-input-lwaClientId').val() || '', scope: 'profile', } return execPostRequest(url, data) } async function ensureValidAccessToken() { //if there is a vshJwt (devices provisioned with v >3.0.0), use it as Bearer token instead of legacy access token if ($('#node-config-input-vshJwt').val()) { return 'Bearer ' + $('#node-config-input-vshJwt').val() } //legacy: 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: $('#node-config-input-lwaClientId').val() || 'xxx', } const resp = await execPostRequest(url, data) if (!resp.access_token) { throw new Error('could not fetch access token') } 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 } 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(getBackendUrl() + '/provision', { accessToken: accessToken, vshVersion: installedVshVersion, }) } function getRegisteredDevices(accessToken) { return execGetRequest(getBackendUrl() + '/devices', { Authorization: accessToken, }) } function getPlanInfo(accessToken) { return execGetRequest(getBackendUrl() + '/plan', { Authorization: accessToken, }) } function checkVersion(version) { return execGetRequest( `${$( '#node-config-input-backendUrl' ).val()}/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( getBackendUrl() + '/device', { Authorization: accessToken }, { thingId, deviceId } ) if (deleteResult.error) { showError('delete failed') $(`#${deviceId}`).fadeIn() } } async function displayPlanInfo() { try { const accessToken = await ensureValidAccessToken() const { plan, allowedDeviceCount, availablePlans, subcriptionToken } = await getPlanInfo(accessToken) $('.current-plan-name').text(plan.toUpperCase()) $('#allowed-device-count').text(allowedDeviceCount) if (plan === 'free') { $('#plan-name').text(availablePlans[0].name) //availablePlans is an array, but at this point we're handling only the first element! const availPlan = availablePlans[0] $.each(availPlan.features, function (i, feature) { let $li = $('<li>').text(feature).appendTo('#plan-features') }) $.each(availPlan.priceTags, async function (i, priceTag) { $('#' + priceTag.name) .text(priceTag.tag) .attr( 'href', getBackendUrl() + '/checkout?token=' + priceTag.checkoutToken ) .on('click', () => $('#buy-subscription').hide()) }) $('#buy-subscription').show() } else { $('#btn-manage-subscription').attr( 'href', getBackendUrl() + '/subscription?token=' + subcriptionToken ) $('#manage-subscription').show() } } catch (e) { console.log(e) } } async function displayRegisteredDevices() { $('#registered-devices').show() let registeredDevices try { const accessToken = await ensureValidAccessToken() registeredDevices = await getRegisteredDevices(accessToken) registeredDeviceCount = registeredDevices.length $('#loading').hide() if (registeredDevices.length == 0) { $('#empty').show() return } } catch (e) { console.log('loading device list failed!', e.message) $('#loading').hide() $('#loading-failed').show() return } // sort by friendlyName 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 }) // beautify template names 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 }) // mark duplicates registeredDevices = registeredDevices.map((item) => { const duplicates = registeredDevices.filter( (d) => d.deviceId == item.deviceId ) item.isDuplicate = duplicates.length > 1 return item }) console.table(registeredDevices) // show only relevant hints below table if ( registeredDevices.some( (d) => d.thingId != $('#node-config-input-thingId').val() ) ) { $('#foreign-connection-hint').show() } if (registeredDevices.some((d) => d.isDuplicate)) { $('#duplicates-hint').show() } $.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>').append( document.createTextNode(item.friendlyName), item.isDuplicate ? $('<i class="is-duplicate fa fa-exclamation-triangle">') : null ), $('<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() } function reactOnConfigChanged() { stopPolling() $('#device-code').hide() showError('Configuration changed! Save changes and re-open this dialog!') } async function oneditprepare() { if (RED.settings.vshConnectionShowSettings) { $('.hidden').show() } $('#node-config-input-backendUrl').val(getBackendUrl()) $('#node-config-input-lwaClientId').val(getLwaClientId()) $('#node-config-input-backendUrl').focusin(reactOnConfigChanged) $('#node-config-input-lwaClientId').focusin(reactOnConfigChanged) if (!this.credentials.email) { $('#backendUrlAndLwaClientId').show() let installedVshVersion try { installedVshVersion = await getInstalledVshVersion() const versionCheckResult = await checkVersion(installedVshVersion) if (!versionCheckResult.isLatestVersion) { return showError( versionCheckResult.updateHint || 'Please update to the latest version of VSH!' ) } } catch (e) { return showError('Could not connect to backend!') } try { const { error_description, device_code, expires_in, interval, user_code, verification_uri, } = await fetchDeviceCode() if (error_description) { //return showError(error) throw new Error(error_description) } 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-vshJwt').val(provisionData.vshJwt) $('#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) { showError(e.message) } } else { $('#provisioned').show() if (RED.settings.vshConnectionShowSettings) { $('.hidden').show() } await displayPlanInfo() await displayRegisteredDevices() } } function oneditsave() { stopPolling() } RED.nodes.registerType('vsh-connection', { category: 'config', paletteLabel: 'connection', defaults: { name: { value: '' }, port: { value: '', required: true }, accessTokenExpiry: { value: 0 }, debug: { value: false }, backendUrl: { value: '', required: true, }, lwaClientId: { value: '', required: true, }, }, credentials: { vshJwt: { type: 'text' }, 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, #manage-subscription, #buy-subscription, #registered-devices, #device-list-table, #loading-failed, #device-code, #backendUrlAndLwaClientId, #empty, #error { display: none; } .hidden { display: none; } #registered-devices > #loading-failed { color: red; } #device-code, #error { padding: 10px; text-align: center; border: 3px red dashed; } .subscription a { color: white; background-color: #00691c; border: 1px solid; border-radius: 10px; padding: 8px; } .subscription a:hover, .subscription a:focus { background-color: #015217; color: white; } #provisioned h1, #registered-devices h1, .subscription > h1 { font-size: 1.5em; margin-top: 30px; } .subscription > h2 { font-size: 1.2em; margin-top: 20px; } #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: rgb(211, 211, 211); } #registered-devices .is-duplicate { padding-left: 10px; color: red; } #table-hints { font-size: 0.8em; margin-top: 10px; margin-bottom: 0; } #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="backendUrlAndLwaClientId"> <div class="form-row hidden"> <label for="node-config-input-backendUrl" ><i class="fa fa-server"></i> Backend URL</label > <input type="text" id="node-config-input-backendUrl" placeholder="Backend URL" /> </div> <div class="form-row hidden"> <label for="node-config-input-lwaClientId" ><i class="fa fa-amazon"></i> LWA Client Id</label > <input type="text" id="node-config-input-lwaClientId" placeholder="LWA Client Id" /> </div> </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 (&lt;<span id="refresh-interval" >REFRESH-INTERVAL</span > sec) </p> <p> <span class="step">4</span> <br /> Close this dialog by clicking the &quot;Add&quot; / &quot;Update&quot; 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-vshJwt" ><i class="fa fa-ticket"></i> VSH JWT</label > <input type="text" id="node-config-input-vshJwt" readonly placeholder="VSH JWT" /> </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-hashtag"></i> Thing ID</label > <input type="text" id="node-config-input-thingId" readonly placeholder="Thing ID" /> </div> <div class="form-row"> <label for="node-config-input-debug" ><i class="fa fa-bug"></i> Debug</label > <input type="checkbox" id="node-config-input-debug" style="display:inline-block;width:22px;vertical-align:top;" autocomplete="off" /> </div> </div> <div id="manage-subscription" class="subscription"> <h1>Subscription</h1> <p>Your current plan: <b class="current-plan-name">{CURRENT-PLAN-NAME}</b></p> <p> <a id="btn-manage-subscription" href="" target="_blank">manage subscription</a> </p> </div> <div id="buy-subscription" class="subscription"> <h1>Subscription</h1> <p>Your current plan: <b class="current-plan-name">{CURRENT-PLAN-NAME}</b></p> <h2>Upgrade to <span id="plan-name">VSH Premium</span>!</h2> <p> <ul id="plan-features"> <!-- <li> elements are dynamically put here --> </ul> </p> <p> Subscribe for <a id="vsh-pro-yearly" href="" target="_blank">XX EUR per year</a> or <a id="vsh-pro-monthly" href="" target="_blank">X.XX EUR per month</a> </p> </div> <div id="registered-devices"> <h1>Registered Devices</h1> <p>The <span class="current-plan-name">{CURRENT-PLAN-NAME}</span> plan allows up to <span id="allowed-device-count">?</span> devices</p> <div id="loading">...loading...</div> <div id="loading-failed">Loading device list failed!</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>&nbsp;</th> </tr> </table> <ul id="table-hints"> <li id="foreign-connection-hint" hidden>Devices from other connections are shown with a gray background</li> <li id="duplicates-hint" hidden><i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Indicates non-unique Device IDs</li> </ul> </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 originating from other connections (possibly even different Node-RED instances) 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>