feat: push notifications on each device (Web Push)
- What reaches the bell also reaches the devices where the person turned «Avisos en este dispositivo» on, with TaskStream closed: the Notifier sends each new notification encrypted (aes128gcm) and signed with VAPID, and forgets subscriptions the push service dropped (404/410). A failure never blocks the event stream. - The API keeps one subscription per device (push_subscriptions) and exposes the VAPID public key in the notification settings; GraphQL subscribePush/unsubscribePush, REST /me/push-subscriptions. Without VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY push is off. - The web registers /push-sw.js, a service worker that only shows the notification and opens its ticket on a tap (no caching, served without cache by nginx), and a manifest that makes it installable, which iPhones need for push. - The bell's toggles show their text next to them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import {
|
||||
PushDevice,
|
||||
PushDeviceSubscription,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
|
||||
/** The service worker that shows the notifications (apps/web/public). */
|
||||
const WORKER = '/push-sw.js';
|
||||
|
||||
/** Push through this browser's service worker and PushManager. */
|
||||
@Injectable()
|
||||
export class BrowserPushDevice extends PushDevice {
|
||||
get supported(): boolean {
|
||||
return (
|
||||
typeof window !== 'undefined' &&
|
||||
'serviceWorker' in navigator &&
|
||||
'PushManager' in window &&
|
||||
'Notification' in window
|
||||
);
|
||||
}
|
||||
|
||||
async current(): Promise<PushDeviceSubscription | null> {
|
||||
if (!this.supported) return null;
|
||||
const registration = await navigator.serviceWorker.getRegistration(WORKER);
|
||||
const subscription = await registration?.pushManager.getSubscription();
|
||||
return subscription ? toDevice(subscription) : null;
|
||||
}
|
||||
|
||||
async subscribe(publicKey: string): Promise<PushDeviceSubscription> {
|
||||
if (!this.supported) throw new Error('Este navegador no admite avisos');
|
||||
if ((await Notification.requestPermission()) !== 'granted')
|
||||
throw new Error(
|
||||
'El navegador no tiene permiso para mostrar avisos: dáselo en los ajustes del sitio.',
|
||||
);
|
||||
const registration = await navigator.serviceWorker.register(WORKER);
|
||||
await navigator.serviceWorker.ready;
|
||||
try {
|
||||
const subscription =
|
||||
(await registration.pushManager.getSubscription()) ??
|
||||
(await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: fromBase64Url(publicKey),
|
||||
}));
|
||||
return toDevice(subscription);
|
||||
} catch {
|
||||
// The browser's own message is in English and says little.
|
||||
throw new Error(
|
||||
'Este navegador no ha dejado activar los avisos. En iPhone, añade antes TaskStream a la pantalla de inicio.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async unsubscribe(): Promise<string | null> {
|
||||
if (!this.supported) return null;
|
||||
const registration = await navigator.serviceWorker.getRegistration(WORKER);
|
||||
const subscription = await registration?.pushManager.getSubscription();
|
||||
if (!subscription) return null;
|
||||
await subscription.unsubscribe();
|
||||
return subscription.endpoint;
|
||||
}
|
||||
}
|
||||
|
||||
function toDevice(subscription: PushSubscription): PushDeviceSubscription {
|
||||
const json = subscription.toJSON();
|
||||
return {
|
||||
endpoint: subscription.endpoint,
|
||||
p256dh: json.keys?.['p256dh'] ?? '',
|
||||
auth: json.keys?.['auth'] ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
/** VAPID keys travel as base64url; PushManager wants the bytes. */
|
||||
function fromBase64Url(text: string): Uint8Array<ArrayBuffer> {
|
||||
const base64 = (text + '='.repeat((4 - (text.length % 4)) % 4))
|
||||
.replace(/-/g, '+')
|
||||
.replace(/_/g, '/');
|
||||
const raw = atob(base64);
|
||||
const bytes = new Uint8Array(new ArrayBuffer(raw.length));
|
||||
for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
|
||||
return bytes;
|
||||
}
|
||||
@@ -3,12 +3,15 @@ import {
|
||||
Notification,
|
||||
NotificationSettings,
|
||||
NotificationsGateway,
|
||||
PushDeviceSubscription,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
import { map, Observable } from 'rxjs';
|
||||
import {
|
||||
MarkNotificationsReadDocument,
|
||||
MyNotificationsDocument,
|
||||
NotificationSettingsDocument,
|
||||
SubscribePushDocument,
|
||||
UnsubscribePushDocument,
|
||||
UpdateNotificationSettingsDocument,
|
||||
} from '../graphql/generated';
|
||||
import { GraphqlOperations } from './graphql-operations';
|
||||
@@ -46,4 +49,16 @@ export class GraphqlNotificationsGateway extends NotificationsGateway {
|
||||
.mutate(UpdateNotificationSettingsDocument, { email })
|
||||
.pipe(map((d) => ({ ...d.updateNotificationSettings })));
|
||||
}
|
||||
|
||||
subscribePush(subscription: PushDeviceSubscription): Observable<void> {
|
||||
return this.gql
|
||||
.mutate(SubscribePushDocument, { subscription })
|
||||
.pipe(map(() => undefined));
|
||||
}
|
||||
|
||||
unsubscribePush(endpoint: string): Observable<void> {
|
||||
return this.gql
|
||||
.mutate(UnsubscribePushDocument, { endpoint })
|
||||
.pipe(map(() => undefined));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user