From 73b500db64634a542675528e1c174983ddd36640 Mon Sep 17 00:00:00 2001 From: Tommy Jonsson Date: Tue, 29 Jan 2019 23:49:41 +0100 Subject: [PATCH] html5 notifications add VAPID support (#2560) * html5 notifications add VAPID support * fix travis error * replace httpapi with websocketapi --- .../ha-push-notifications-toggle.js | 18 +++++++++++++++- src/data/notify_html5.ts | 21 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 src/data/notify_html5.ts diff --git a/src/components/ha-push-notifications-toggle.js b/src/components/ha-push-notifications-toggle.js index d5078f6978..85175947df 100644 --- a/src/components/ha-push-notifications-toggle.js +++ b/src/components/ha-push-notifications-toggle.js @@ -2,6 +2,8 @@ import "@polymer/paper-toggle-button/paper-toggle-button"; import { html } from "@polymer/polymer/lib/utils/html-tag"; import { PolymerElement } from "@polymer/polymer/polymer-element"; +import { getAppKey } from "../data/notify_html5"; + import EventsMixin from "../mixins/events-mixin"; export const pushSupported = @@ -93,7 +95,21 @@ class HaPushNotificationsToggle extends EventsMixin(PolymerElement) { return; } - sub = await reg.pushManager.subscribe({ userVisibleOnly: true }); + let applicationServerKey; + try { + applicationServerKey = await getAppKey(this.hass); + } catch (ex) { + applicationServerKey = null; + } + + if (applicationServerKey) { + sub = await reg.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey, + }); + } else { + sub = await reg.pushManager.subscribe({ userVisibleOnly: true }); + } await this.hass.callApi("POST", "notify.html5", { subscription: sub, diff --git a/src/data/notify_html5.ts b/src/data/notify_html5.ts new file mode 100644 index 0000000000..9aa643168a --- /dev/null +++ b/src/data/notify_html5.ts @@ -0,0 +1,21 @@ +import { HomeAssistant } from "../types"; + +function urlBase64ToUint8Array(base64String) { + const padding = "=".repeat((4 - (base64String.length % 4)) % 4); + const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/"); + + const rawData = window.atob(base64); + const outputArray = new Uint8Array(rawData.length); + + for (let i = 0; i < rawData.length; ++i) { + outputArray[i] = rawData.charCodeAt(i); + } + return outputArray; +} + +export const getAppKey = async (hass: HomeAssistant) => { + const res = await hass.callWS({ + type: "notify/html5/appkey", + }); + return res ? urlBase64ToUint8Array(res) : null; +};