html5 notifications add VAPID support (#2560)

* html5 notifications add VAPID support

* fix travis error

* replace httpapi with websocketapi
This commit is contained in:
Tommy Jonsson 2019-01-29 23:49:41 +01:00 committed by Paulus Schoutsen
parent a090b291aa
commit 73b500db64
2 changed files with 38 additions and 1 deletions

View File

@ -2,6 +2,8 @@ import "@polymer/paper-toggle-button/paper-toggle-button";
import { html } from "@polymer/polymer/lib/utils/html-tag"; import { html } from "@polymer/polymer/lib/utils/html-tag";
import { PolymerElement } from "@polymer/polymer/polymer-element"; import { PolymerElement } from "@polymer/polymer/polymer-element";
import { getAppKey } from "../data/notify_html5";
import EventsMixin from "../mixins/events-mixin"; import EventsMixin from "../mixins/events-mixin";
export const pushSupported = export const pushSupported =
@ -93,7 +95,21 @@ class HaPushNotificationsToggle extends EventsMixin(PolymerElement) {
return; 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", { await this.hass.callApi("POST", "notify.html5", {
subscription: sub, subscription: sub,

21
src/data/notify_html5.ts Normal file
View File

@ -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<string>({
type: "notify/html5/appkey",
});
return res ? urlBase64ToUint8Array(res) : null;
};