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:
@@ -1,6 +1,7 @@
|
||||
export * from './lib/notifications';
|
||||
export * from './lib/facades/projects.facade';
|
||||
export * from './lib/facades/calendar.facade';
|
||||
export * from './lib/facades/push.facade';
|
||||
export * from './lib/facades/project.facade';
|
||||
export * from './lib/facades/board.facade';
|
||||
export * from './lib/facades/issue.facade';
|
||||
|
||||
60
libs/web/tracker/application/src/lib/facades/push.facade.ts
Normal file
60
libs/web/tracker/application/src/lib/facades/push.facade.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { inject, Injectable, signal } from '@angular/core';
|
||||
import {
|
||||
NotificationsGateway,
|
||||
PushDevice,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
|
||||
/**
|
||||
* Push on this device: the browser subscribes and the API keeps it, so the
|
||||
* notifications of the bell also reach the device with TaskStream closed.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class PushFacade {
|
||||
private readonly device = inject(PushDevice);
|
||||
private readonly gateway = inject(NotificationsGateway);
|
||||
|
||||
readonly supported = this.device.supported;
|
||||
readonly on = signal(false);
|
||||
readonly busy = signal(false);
|
||||
readonly error = signal<string | null>(null);
|
||||
|
||||
/** Whether this browser has push on now. */
|
||||
async refresh(): Promise<void> {
|
||||
this.on.set(!!(await this.device.current().catch(() => null)));
|
||||
}
|
||||
|
||||
async turnOn(publicKey: string): Promise<void> {
|
||||
await this.run(async () => {
|
||||
const subscription = await this.device.subscribe(publicKey);
|
||||
await firstValueFrom(this.gateway.subscribePush(subscription));
|
||||
this.on.set(true);
|
||||
});
|
||||
}
|
||||
|
||||
async turnOff(): Promise<void> {
|
||||
await this.run(async () => {
|
||||
const endpoint = await this.device.unsubscribe();
|
||||
if (endpoint)
|
||||
await firstValueFrom(this.gateway.unsubscribePush(endpoint));
|
||||
this.on.set(false);
|
||||
});
|
||||
}
|
||||
|
||||
private async run(step: () => Promise<void>): Promise<void> {
|
||||
this.busy.set(true);
|
||||
this.error.set(null);
|
||||
try {
|
||||
await step();
|
||||
} catch (error) {
|
||||
this.error.set(
|
||||
error instanceof Error && error.message
|
||||
? error.message
|
||||
: 'No se han podido activar los avisos',
|
||||
);
|
||||
await this.refresh();
|
||||
} finally {
|
||||
this.busy.set(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -441,4 +441,13 @@ export interface NotificationSettings {
|
||||
email: boolean;
|
||||
/** Whether this installation can send e-mail at all. */
|
||||
emailAvailable: boolean;
|
||||
/** VAPID key to subscribe a device to push with; null: no push here. */
|
||||
pushPublicKey: string | null;
|
||||
}
|
||||
|
||||
/** A browser's Web Push subscription, as the API takes it. */
|
||||
export interface PushDeviceSubscription {
|
||||
endpoint: string;
|
||||
p256dh: string;
|
||||
auth: string;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
AutomationInput,
|
||||
BoardColumn,
|
||||
CalendarFeed,
|
||||
PushDeviceSubscription,
|
||||
CommandResult,
|
||||
Comment,
|
||||
Epic,
|
||||
@@ -350,6 +351,26 @@ export abstract class NotificationsGateway {
|
||||
abstract markRead(ids?: string[]): Observable<void>;
|
||||
abstract settings(): Observable<NotificationSettings>;
|
||||
abstract updateSettings(email: boolean): Observable<NotificationSettings>;
|
||||
/** Push on this device. */
|
||||
abstract subscribePush(
|
||||
subscription: PushDeviceSubscription,
|
||||
): Observable<void>;
|
||||
/** Push off on this device. */
|
||||
abstract unsubscribePush(endpoint: string): Observable<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* This browser's side of push: its service worker and push subscription.
|
||||
* Not every browser has it (and on iPhone only an installed web app does).
|
||||
*/
|
||||
export abstract class PushDevice {
|
||||
abstract get supported(): boolean;
|
||||
/** This browser's subscription, if push is on here. */
|
||||
abstract current(): Promise<PushDeviceSubscription | null>;
|
||||
/** Asks for permission and subscribes; throws when refused. */
|
||||
abstract subscribe(publicKey: string): Promise<PushDeviceSubscription>;
|
||||
/** Unsubscribes; the endpoint it had, if any. */
|
||||
abstract unsubscribe(): Promise<string | null>;
|
||||
}
|
||||
|
||||
/** Realtime (GraphQL subscriptions over WebSocket). */
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,6 +236,13 @@ export type ProjectSettingsInput = {
|
||||
transitions: Array<StatusTransitionsInput>;
|
||||
};
|
||||
|
||||
/** A browser's Web Push subscription (PushSubscription.toJSON()) */
|
||||
export type PushSubscriptionInput = {
|
||||
auth: string;
|
||||
endpoint: string;
|
||||
p256dh: string;
|
||||
};
|
||||
|
||||
export type RankIssueInput = {
|
||||
/** The ticket that ends up right above (null: the top) */
|
||||
aboveIssueId?: string | null | undefined;
|
||||
@@ -1366,7 +1373,11 @@ export type NotificationSettingsQueryVariables = Exact<{
|
||||
}>;
|
||||
|
||||
export type NotificationSettingsQuery = {
|
||||
notificationSettings: { email: boolean; emailAvailable: boolean };
|
||||
notificationSettings: {
|
||||
email: boolean;
|
||||
emailAvailable: boolean;
|
||||
pushPublicKey: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
export type MarkNotificationsReadMutationVariables = Exact<{
|
||||
@@ -1380,9 +1391,25 @@ export type UpdateNotificationSettingsMutationVariables = Exact<{
|
||||
}>;
|
||||
|
||||
export type UpdateNotificationSettingsMutation = {
|
||||
updateNotificationSettings: { email: boolean; emailAvailable: boolean };
|
||||
updateNotificationSettings: {
|
||||
email: boolean;
|
||||
emailAvailable: boolean;
|
||||
pushPublicKey: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
export type SubscribePushMutationVariables = Exact<{
|
||||
subscription: PushSubscriptionInput;
|
||||
}>;
|
||||
|
||||
export type SubscribePushMutation = { subscribePush: boolean };
|
||||
|
||||
export type UnsubscribePushMutationVariables = Exact<{
|
||||
endpoint: string;
|
||||
}>;
|
||||
|
||||
export type UnsubscribePushMutation = { unsubscribePush: boolean };
|
||||
|
||||
export type NotificationAddedSubscriptionVariables = Exact<{
|
||||
[key: string]: never;
|
||||
}>;
|
||||
@@ -8442,6 +8469,10 @@ export const NotificationSettingsDocument = {
|
||||
kind: 'Field',
|
||||
name: { kind: 'Name', value: 'emailAvailable' },
|
||||
},
|
||||
{
|
||||
kind: 'Field',
|
||||
name: { kind: 'Name', value: 'pushPublicKey' },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
@@ -8545,6 +8576,10 @@ export const UpdateNotificationSettingsDocument = {
|
||||
kind: 'Field',
|
||||
name: { kind: 'Name', value: 'emailAvailable' },
|
||||
},
|
||||
{
|
||||
kind: 'Field',
|
||||
name: { kind: 'Name', value: 'pushPublicKey' },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
@@ -8556,6 +8591,102 @@ export const UpdateNotificationSettingsDocument = {
|
||||
UpdateNotificationSettingsMutation,
|
||||
UpdateNotificationSettingsMutationVariables
|
||||
>;
|
||||
export const SubscribePushDocument = {
|
||||
kind: 'Document',
|
||||
definitions: [
|
||||
{
|
||||
kind: 'OperationDefinition',
|
||||
operation: 'mutation',
|
||||
name: { kind: 'Name', value: 'SubscribePush' },
|
||||
variableDefinitions: [
|
||||
{
|
||||
kind: 'VariableDefinition',
|
||||
variable: {
|
||||
kind: 'Variable',
|
||||
name: { kind: 'Name', value: 'subscription' },
|
||||
},
|
||||
type: {
|
||||
kind: 'NonNullType',
|
||||
type: {
|
||||
kind: 'NamedType',
|
||||
name: { kind: 'Name', value: 'PushSubscriptionInput' },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
selectionSet: {
|
||||
kind: 'SelectionSet',
|
||||
selections: [
|
||||
{
|
||||
kind: 'Field',
|
||||
name: { kind: 'Name', value: 'subscribePush' },
|
||||
arguments: [
|
||||
{
|
||||
kind: 'Argument',
|
||||
name: { kind: 'Name', value: 'subscription' },
|
||||
value: {
|
||||
kind: 'Variable',
|
||||
name: { kind: 'Name', value: 'subscription' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
} as unknown as DocumentNode<
|
||||
SubscribePushMutation,
|
||||
SubscribePushMutationVariables
|
||||
>;
|
||||
export const UnsubscribePushDocument = {
|
||||
kind: 'Document',
|
||||
definitions: [
|
||||
{
|
||||
kind: 'OperationDefinition',
|
||||
operation: 'mutation',
|
||||
name: { kind: 'Name', value: 'UnsubscribePush' },
|
||||
variableDefinitions: [
|
||||
{
|
||||
kind: 'VariableDefinition',
|
||||
variable: {
|
||||
kind: 'Variable',
|
||||
name: { kind: 'Name', value: 'endpoint' },
|
||||
},
|
||||
type: {
|
||||
kind: 'NonNullType',
|
||||
type: {
|
||||
kind: 'NamedType',
|
||||
name: { kind: 'Name', value: 'String' },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
selectionSet: {
|
||||
kind: 'SelectionSet',
|
||||
selections: [
|
||||
{
|
||||
kind: 'Field',
|
||||
name: { kind: 'Name', value: 'unsubscribePush' },
|
||||
arguments: [
|
||||
{
|
||||
kind: 'Argument',
|
||||
name: { kind: 'Name', value: 'endpoint' },
|
||||
value: {
|
||||
kind: 'Variable',
|
||||
name: { kind: 'Name', value: 'endpoint' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
} as unknown as DocumentNode<
|
||||
UnsubscribePushMutation,
|
||||
UnsubscribePushMutationVariables
|
||||
>;
|
||||
export const NotificationAddedDocument = {
|
||||
kind: 'Document',
|
||||
definitions: [
|
||||
|
||||
@@ -26,6 +26,7 @@ query NotificationSettings {
|
||||
notificationSettings {
|
||||
email
|
||||
emailAvailable
|
||||
pushPublicKey
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,9 +38,18 @@ mutation UpdateNotificationSettings($email: Boolean!) {
|
||||
updateNotificationSettings(email: $email) {
|
||||
email
|
||||
emailAvailable
|
||||
pushPublicKey
|
||||
}
|
||||
}
|
||||
|
||||
mutation SubscribePush($subscription: PushSubscriptionInput!) {
|
||||
subscribePush(subscription: $subscription)
|
||||
}
|
||||
|
||||
mutation UnsubscribePush($endpoint: String!) {
|
||||
unsubscribePush(endpoint: $endpoint)
|
||||
}
|
||||
|
||||
subscription NotificationAdded {
|
||||
notificationAdded {
|
||||
...NotificationFields
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
IssuesGateway,
|
||||
NotificationsGateway,
|
||||
CalendarGateway,
|
||||
PushDevice,
|
||||
ProjectsGateway,
|
||||
ReleasesGateway,
|
||||
SavedFiltersGateway,
|
||||
@@ -30,6 +31,7 @@ import {
|
||||
import { GraphqlIssuesGateway } from './adapters/graphql-issues.gateway';
|
||||
import { GraphqlNotificationsGateway } from './adapters/graphql-notifications.gateway';
|
||||
import { GraphqlCalendarGateway } from './adapters/graphql-calendar.gateway';
|
||||
import { BrowserPushDevice } from './adapters/browser-push.device';
|
||||
import { HttpAttachmentsGateway } from './adapters/http-attachments.gateway';
|
||||
import { HttpProposalsGateway } from './adapters/http-proposals.gateway';
|
||||
import { GraphqlProjectsGateway } from './adapters/graphql-projects.gateway';
|
||||
@@ -54,6 +56,7 @@ export function provideTrackerInfrastructure(): EnvironmentProviders {
|
||||
{ provide: UsersGateway, useClass: GraphqlUsersGateway },
|
||||
{ provide: NotificationsGateway, useClass: GraphqlNotificationsGateway },
|
||||
{ provide: CalendarGateway, useClass: GraphqlCalendarGateway },
|
||||
{ provide: PushDevice, useClass: BrowserPushDevice },
|
||||
{ provide: TrackerRealtimeGateway, useClass: GraphqlRealtimeGateway },
|
||||
{ provide: SavedFiltersGateway, useClass: GraphqlSavedFiltersGateway },
|
||||
{ provide: SprintsGateway, useClass: GraphqlSprintsGateway },
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
PiSlideToggleComponent,
|
||||
} from '@pi/ui';
|
||||
import { DrawerService } from '@task-stream/web/shared/ui';
|
||||
import { InboxFacade } from '@task-stream/web/tracker/application';
|
||||
import { InboxFacade, PushFacade } from '@task-stream/web/tracker/application';
|
||||
import {
|
||||
Notification,
|
||||
NotificationKind,
|
||||
@@ -81,13 +81,30 @@ const ICON: Record<NotificationKind, string> = {
|
||||
(execute)="inbox.markRead()"
|
||||
/>
|
||||
@if (inbox.settings()?.emailAvailable) {
|
||||
<pi-slide-toggle
|
||||
label="Copia por correo"
|
||||
[checked]="inbox.settings()?.email ?? false"
|
||||
(checkedChange)="inbox.setEmail($event)"
|
||||
/>
|
||||
<div class="ts-inbox__switch">
|
||||
<pi-slide-toggle
|
||||
label="Copia por correo"
|
||||
[checked]="inbox.settings()?.email ?? false"
|
||||
(checkedChange)="inbox.setEmail($event)"
|
||||
/>
|
||||
<span aria-hidden="true">Copia por correo</span>
|
||||
</div>
|
||||
}
|
||||
@if (inbox.settings()?.pushPublicKey && push.supported) {
|
||||
<div class="ts-inbox__switch">
|
||||
<pi-slide-toggle
|
||||
label="Avisos en este dispositivo"
|
||||
[checked]="push.on()"
|
||||
[disabled]="push.busy()"
|
||||
(checkedChange)="togglePush($event)"
|
||||
/>
|
||||
<span aria-hidden="true">Avisos en este dispositivo</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
@if (push.error(); as error) {
|
||||
<p class="ts-inbox__error" role="alert">{{ error }}</p>
|
||||
}
|
||||
@if (inbox.items().length) {
|
||||
<ul class="ts-inbox__list">
|
||||
@for (item of inbox.items(); track item.id) {
|
||||
@@ -139,6 +156,17 @@ const ICON: Record<NotificationKind, string> = {
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.ts-inbox__switch {
|
||||
display: inline-flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
.ts-inbox__error {
|
||||
margin: 0;
|
||||
color: var(--ts-c-red, var(--ts-ink));
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
.ts-inbox__list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
@@ -201,6 +229,7 @@ const ICON: Record<NotificationKind, string> = {
|
||||
})
|
||||
export class NotificationsBell {
|
||||
protected readonly inbox = inject(InboxFacade);
|
||||
protected readonly push = inject(PushFacade);
|
||||
private readonly drawer = inject(DrawerService);
|
||||
private readonly router = inject(Router);
|
||||
private readonly panel = viewChild.required<TemplateRef<unknown>>('panel');
|
||||
@@ -209,9 +238,16 @@ export class NotificationsBell {
|
||||
protected icon = (item: Notification) => ICON[item.kind] ?? 'info';
|
||||
|
||||
protected open(): void {
|
||||
void this.push.refresh();
|
||||
this.drawer.open('Notificaciones', this.panel(), '28rem');
|
||||
}
|
||||
|
||||
protected togglePush(on: boolean): void {
|
||||
const key = this.inbox.settings()?.pushPublicKey;
|
||||
if (on && key) void this.push.turnOn(key);
|
||||
else if (!on) void this.push.turnOff();
|
||||
}
|
||||
|
||||
protected go(item: Notification): void {
|
||||
if (!item.readAt) this.inbox.markRead([item.id]);
|
||||
this.drawer.closeAll();
|
||||
|
||||
Reference in New Issue
Block a user