Improved push notifications

This commit is contained in:
2017-07-15 01:32:06 +02:00
parent 92a540e024
commit 460d90d957
7 changed files with 78 additions and 22 deletions

@ -215,13 +215,15 @@ export function search(arn: AnimeNotifier, search: HTMLInputElement, e: Keyboard
}
// Enable notifications
export function enableNotifications(arn: AnimeNotifier, button: HTMLElement) {
arn.pushManager.subscribe(arn.user.dataset.id)
export async function enableNotifications(arn: AnimeNotifier, button: HTMLElement) {
await arn.pushManager.subscribe(arn.user.dataset.id)
arn.updatePushUI()
}
// Disable notifications
export function disableNotifications(arn: AnimeNotifier, button: HTMLElement) {
arn.pushManager.unsubscribe(arn.user.dataset.id)
export async function disableNotifications(arn: AnimeNotifier, button: HTMLElement) {
await arn.pushManager.unsubscribe(arn.user.dataset.id)
arn.updatePushUI()
}
// Test notification

@ -111,7 +111,7 @@ export class AnimeNotifier {
this.pushManager = new PushManager()
}
onContentLoaded() {
async onContentLoaded() {
// Stop watching all the objects from the previous page.
this.visibilityObserver.disconnect()
@ -120,9 +120,11 @@ export class AnimeNotifier {
Promise.resolve().then(() => this.lazyLoadImages()),
Promise.resolve().then(() => this.displayLocalDates()),
Promise.resolve().then(() => this.setSelectBoxValue()),
Promise.resolve().then(() => this.assignActions())
Promise.resolve().then(() => this.assignActions()),
Promise.resolve().then(() => this.updatePushUI())
])
// Apply page title
let headers = document.getElementsByTagName("h1")
if(this.app.currentPath === "/" || headers.length === 0) {
@ -134,6 +136,22 @@ export class AnimeNotifier {
}
}
async updatePushUI() {
if(!this.pushManager.pushSupported) {
return
}
let subscription = await this.pushManager.subscription()
if(subscription) {
this.app.find("enable-notifications").style.display = "none"
this.app.find("disable-notifications").style.display = "flex"
} else {
this.app.find("enable-notifications").style.display = "flex"
this.app.find("disable-notifications").style.display = "none"
}
}
onIdle() {
this.pushAnalytics()
}

@ -5,6 +5,21 @@ export class PushManager {
this.pushSupported = ("serviceWorker" in navigator) && ("PushManager" in window)
}
async subscription(): Promise<PushSubscription> {
if(!this.pushSupported) {
return Promise.resolve(null)
}
let registration = await navigator.serviceWorker.ready
let subscription = await registration.pushManager.getSubscription()
if(subscription) {
return Promise.resolve(subscription)
}
return Promise.resolve(null)
}
async subscribe(userId: string) {
if(!this.pushSupported) {
return
@ -59,6 +74,7 @@ export class PushManager {
p256dh: key,
auth: secret,
platform: navigator.platform,
userAgent: navigator.userAgent,
screen: {
width: window.screen.width,
height: window.screen.height