Skip to content

Commit

Permalink
webpush finally done
Browse files Browse the repository at this point in the history
  • Loading branch information
zyxkad committed Mar 21, 2024
1 parent 7b75d8f commit 6877264
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 15 deletions.
5 changes: 1 addition & 4 deletions dashboard/src/cookies/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,7 @@ export function bindRefToLocalStorage<T>(
return ref
}

export function bindObjectToLocalStorage<T extends object>(
obj: T,
name: string,
): T {
export function bindObjectToLocalStorage<T extends object>(obj: T, name: string): T {
const active = reactive(obj) as T
const s = localStorage.getItem(name)
if (s) {
Expand Down
56 changes: 55 additions & 1 deletion dashboard/src/sw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ import { NavigationRoute, registerRoute } from 'workbox-routing'

declare let self: ServiceWorkerGlobalScope

const BASE_URL = (() => {
return import.meta.env.BASE_URL.endsWith('/')
? import.meta.env.BASE_URL.substr(0, import.meta.env.BASE_URL.length - 1)
: import.meta.env.BASE_URL
})()
const ICON_URL = BASE_URL + '/favicon.ico'

console.log('PWA Service worker loading')

// self.__WB_MANIFEST is default injection point
Expand All @@ -28,9 +35,48 @@ async function onSyncUserSettings(): Promise<void> {
// axios.get()
}

type PushData =
| {
typ: 'enabled' | 'disabled' | 'syncdone'
at: number
}
| {
typ: 'updates'
tag: string
}

async function onRecvPush(data: PushData): Promise<void> {
switch (data.typ) {
case 'enabled':
case 'disabled':
case 'syncdone':
await self.registration
.showNotification('OpenBmclApi', {
icon: ICON_URL,
body: `Cluster ${data.typ}`,
tag: `status-${data.typ}`,
})
.catch((err) => console.error('notify error:', err))
break
case 'updates':
await self.registration
.showNotification('OpenBmclApi', {
icon: ICON_URL,
body: `New version (${data.tag}) avaliable`,
tag: 'update-notify',
})
.catch((err) => console.error('notify error:', err))
break
}
}

async function onNotificationClick(tag: string): Promise<void> {
switch (tag) {
case 'sync': {
case 'updates': {
self.clients.openWindow('https://github.com/LiterMC/go-openbmclapi/releases')
return
}
default: {
const windowClients = await self.clients.matchAll({ type: 'window' })
for (const client of windowClients) {
client.focus()
Expand All @@ -50,6 +96,14 @@ self.addEventListener('sync', (event: SyncEvent) => {
}
})

self.addEventListener('push', (event: PushEvent) => {
if (!event.data) {
return
}
const data = event.data.json()
event.waitUntil(onRecvPush(data))
})

self.addEventListener('notificationclick', (event: NotificationEvent) => {
event.notification.close()
event.waitUntil(onNotificationClick(event.notification.tag))
Expand Down
16 changes: 9 additions & 7 deletions dashboard/src/views/SettingsView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,15 @@ const selectedLang = computed({
const requestingPermission = ref(false)
const enableNotify = ref(false)
const settings = bindObjectToLocalStorage({
notifyWhenDisabled: false,
notifyWhenEnabled: false,
notifyWhenSyncFinished: false,
notifyUpdates: false,
}, 'go-openbmclapi.settings.notify')
const settings = bindObjectToLocalStorage(
{
notifyWhenDisabled: false,
notifyWhenEnabled: false,
notifyWhenSyncFinished: false,
notifyUpdates: false,
},
'go-openbmclapi.settings.notify',
)
function getSubscribeScopes(): SubscribeScope[] {
const res: SubscribeScope[] = []
Expand Down Expand Up @@ -158,7 +161,6 @@ onMounted(() => {
requestingPermission.value = false
})
})
</script>
<template>
<div>
Expand Down
2 changes: 1 addition & 1 deletion database/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ func (db *SqlDB) ForEachSubscribe(cb func(*SubscribeRecord) error) (err error) {
defer cancel()

var rows *sql.Rows
if rows, err = db.subscribeStmts.remove.QueryContext(ctx); err != nil {
if rows, err = db.subscribeStmts.forEach.QueryContext(ctx); err != nil {
return
}
defer rows.Close()
Expand Down
8 changes: 6 additions & 2 deletions webpush.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,13 +229,17 @@ func (w *WebPushManager) SendNotification(ctx context.Context, message []byte, s
}

func (w *WebPushManager) sendMessageIf(ctx context.Context, message []byte, opts *PushOptions, filter func(*database.SubscribeRecord) bool) {
log.Debugf("Sending notification: %s", message)
var wg sync.WaitGroup
w.database.ForEachSubscribe(func(record *database.SubscribeRecord) error {
if filter(record) {
wg.Add(1)
go func(subs *Subscription) {
defer wg.Done()
w.SendNotification(ctx, message, subs, opts)
err := w.SendNotification(ctx, message, subs, opts)
if err != nil {
log.Warnf("Error when sending notification: %v", err)
}
}(&Subscription{
EndPoint: record.EndPoint,
Keys: record.Keys,
Expand Down Expand Up @@ -267,7 +271,7 @@ func (w *WebPushManager) OnEnabled() {

func (w *WebPushManager) OnDisabled() {
message, err := json.Marshal(Map{
"typ": "enabled",
"typ": "disabled",
"at": time.Now().UnixMilli(),
})
if err != nil {
Expand Down

0 comments on commit 6877264

Please sign in to comment.