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:
@@ -4,6 +4,8 @@ import { NotificationReadModel } from '@task-stream/api/tracker/domain';
|
||||
import { SendDueRemindersCommand } from './notifications/reminders';
|
||||
import {
|
||||
MarkNotificationsReadCommand,
|
||||
SubscribePushCommand,
|
||||
UnsubscribePushCommand,
|
||||
UpdateNotificationSettingsCommand,
|
||||
} from './notifications/notifications.commands';
|
||||
import {
|
||||
@@ -37,6 +39,24 @@ export class NotificationsService {
|
||||
}
|
||||
|
||||
/** `ids` omitted: everything. */
|
||||
/** Push on this device (a browser's Web Push subscription). */
|
||||
subscribePush(
|
||||
userId: string,
|
||||
endpoint: string,
|
||||
keys: { p256dh: string; auth: string },
|
||||
): Promise<void> {
|
||||
return this.commandBus.execute(
|
||||
new SubscribePushCommand(userId, endpoint, keys),
|
||||
);
|
||||
}
|
||||
|
||||
/** Push off on this device. */
|
||||
unsubscribePush(userId: string, endpoint: string): Promise<void> {
|
||||
return this.commandBus.execute(
|
||||
new UnsubscribePushCommand(userId, endpoint),
|
||||
);
|
||||
}
|
||||
|
||||
/** Tells of the tickets due around `day` (YYYY-MM-DD); how many it sent. */
|
||||
sendDueReminders(day: string): Promise<number> {
|
||||
return this.commandBus.execute(new SendDueRemindersCommand(day));
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { Command, CommandHandler, ICommandHandler } from '@nestjs/cqrs';
|
||||
import { assertThat } from '@task-stream/api/shared/domain';
|
||||
import { NotificationsRepository } from '../ports/notifications.repository';
|
||||
import { PushSender } from '../ports/push-sender';
|
||||
import { PushSubscriptionsRepository } from '../ports/push-subscriptions.repository';
|
||||
|
||||
/*
|
||||
* Per-person state, outside the event store: whether a notification was read
|
||||
@@ -49,3 +52,64 @@ export class UpdateNotificationSettingsCommandHandler
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Push on this device: the browser's subscription is kept for its owner. */
|
||||
export class SubscribePushCommand extends Command<void> {
|
||||
constructor(
|
||||
public readonly userId: string,
|
||||
public readonly endpoint: string,
|
||||
public readonly keys: { p256dh: string; auth: string },
|
||||
) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
/** Push off on this device. */
|
||||
export class UnsubscribePushCommand extends Command<void> {
|
||||
constructor(
|
||||
public readonly userId: string,
|
||||
public readonly endpoint: string,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
@CommandHandler(SubscribePushCommand)
|
||||
export class SubscribePushCommandHandler
|
||||
implements ICommandHandler<SubscribePushCommand>
|
||||
{
|
||||
constructor(
|
||||
private readonly subscriptions: PushSubscriptionsRepository,
|
||||
private readonly push: PushSender,
|
||||
) {}
|
||||
|
||||
async execute(command: SubscribePushCommand): Promise<void> {
|
||||
assertThat(!!this.push.publicKey, 'Push is not set up here');
|
||||
// Push services are https; anything else is not a browser's endpoint.
|
||||
assertThat(
|
||||
/^https:\/\/[^\s]{8,2000}$/.test(command.endpoint),
|
||||
'Not a push endpoint',
|
||||
);
|
||||
assertThat(
|
||||
!!command.keys?.p256dh && !!command.keys?.auth,
|
||||
'The subscription keys are missing',
|
||||
);
|
||||
await this.subscriptions.save({
|
||||
userId: command.userId,
|
||||
endpoint: command.endpoint,
|
||||
keys: { p256dh: command.keys.p256dh, auth: command.keys.auth },
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@CommandHandler(UnsubscribePushCommand)
|
||||
export class UnsubscribePushCommandHandler
|
||||
implements ICommandHandler<UnsubscribePushCommand>
|
||||
{
|
||||
constructor(private readonly subscriptions: PushSubscriptionsRepository) {}
|
||||
|
||||
async execute(command: UnsubscribePushCommand): Promise<void> {
|
||||
await this.subscriptions.remove(command.userId, command.endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { IQueryHandler, Query, QueryHandler } from '@nestjs/cqrs';
|
||||
import { NotificationReadModel } from '@task-stream/api/tracker/domain';
|
||||
import { NotificationMailer } from '../ports/notification-mailer';
|
||||
import { PushSender } from '../ports/push-sender';
|
||||
import { NotificationsRepository } from '../ports/notifications.repository';
|
||||
|
||||
export interface MyNotifications {
|
||||
@@ -13,6 +14,8 @@ export interface MyNotificationSettings {
|
||||
email: boolean;
|
||||
/** Whether this installation can send e-mail at all. */
|
||||
emailAvailable: boolean;
|
||||
/** VAPID public key to subscribe a device with; null: no push here. */
|
||||
pushPublicKey: string | null;
|
||||
}
|
||||
|
||||
export class GetMyNotificationsQuery extends Query<MyNotifications> {
|
||||
@@ -57,6 +60,7 @@ export class GetMyNotificationSettingsQueryHandler
|
||||
constructor(
|
||||
private readonly notifications: NotificationsRepository,
|
||||
private readonly mailer: NotificationMailer,
|
||||
private readonly push: PushSender,
|
||||
) {}
|
||||
|
||||
async execute(
|
||||
@@ -66,6 +70,7 @@ export class GetMyNotificationSettingsQueryHandler
|
||||
return {
|
||||
email: this.mailer.enabled && settings.email,
|
||||
emailAvailable: this.mailer.enabled,
|
||||
pushPublicKey: this.push.publicKey,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,12 @@ import { NotificationMailer } from '../ports/notification-mailer';
|
||||
import { NotificationsRepository } from '../ports/notifications.repository';
|
||||
import { NotificationsEventHandler } from './notifications.event-handler';
|
||||
import { Notifier } from './notifier';
|
||||
import {
|
||||
PushPayload,
|
||||
PushSender,
|
||||
PushSubscriptionRecord,
|
||||
} from '../ports/push-sender';
|
||||
import { PushSubscriptionsRepository } from '../ports/push-subscriptions.repository';
|
||||
|
||||
class InMemoryNotifications extends NotificationsRepository {
|
||||
readonly all: NotificationReadModel[] = [];
|
||||
@@ -56,10 +62,14 @@ const at = <T extends TrackerEvent>(event: T, version = 2): T =>
|
||||
occurredAt: '2026-10-08T10:00:00.000Z',
|
||||
});
|
||||
|
||||
function setup(mailEnabled = false) {
|
||||
function setup(mailEnabled = false, pushEnabled = false) {
|
||||
const repo = new InMemoryNotifications();
|
||||
const published: NotificationReadModel[] = [];
|
||||
const mailed: string[] = [];
|
||||
/** Endpoint → what was pushed to it. */
|
||||
const pushed: [string, PushPayload][] = [];
|
||||
const devices: PushSubscriptionRecord[] = [];
|
||||
const forgotten: string[] = [];
|
||||
const users = new FakeUserDirectory()
|
||||
.add('ana')
|
||||
.add('bob')
|
||||
@@ -90,6 +100,21 @@ function setup(mailEnabled = false) {
|
||||
},
|
||||
} as unknown as NotificationMailer,
|
||||
users,
|
||||
{
|
||||
publicKey: pushEnabled ? 'vapid-public' : null,
|
||||
send: async (device: PushSubscriptionRecord, payload: PushPayload) => {
|
||||
pushed.push([device.endpoint, payload]);
|
||||
// A browser that dropped the subscription.
|
||||
return device.endpoint.endsWith('/gone') ? 'gone' : 'sent';
|
||||
},
|
||||
} as unknown as PushSender,
|
||||
{
|
||||
forUser: async (userId: string) =>
|
||||
devices.filter((d) => d.userId === userId),
|
||||
forget: async (endpoint: string) => {
|
||||
forgotten.push(endpoint);
|
||||
},
|
||||
} as unknown as PushSubscriptionsRepository,
|
||||
);
|
||||
const handler = new NotificationsEventHandler(
|
||||
notifier,
|
||||
@@ -118,7 +143,7 @@ function setup(mailEnabled = false) {
|
||||
id === 's-14' ? { id, name: 'Sprint 14' } : null,
|
||||
} as unknown as FindSprintsRepository,
|
||||
);
|
||||
return { repo, published, mailed, handler };
|
||||
return { repo, published, mailed, pushed, devices, forgotten, handler };
|
||||
}
|
||||
|
||||
describe('notifications', () => {
|
||||
@@ -340,4 +365,32 @@ describe('notifications', () => {
|
||||
NotificationKind.ADDED_TO_PROJECT,
|
||||
]);
|
||||
});
|
||||
|
||||
it('pushes to every device of whoever is told, and forgets dropped ones', async () => {
|
||||
const { handler, pushed, devices, forgotten } = setup(false, true);
|
||||
const device = (userId: string, endpoint: string) => ({
|
||||
userId,
|
||||
endpoint,
|
||||
keys: { p256dh: 'p', auth: 'a' },
|
||||
createdAt: '2026-10-01T00:00:00.000Z',
|
||||
});
|
||||
devices.push(
|
||||
device('bob', 'https://push.example/phone'),
|
||||
device('bob', 'https://push.example/gone'),
|
||||
device('qa', 'https://push.example/qa'),
|
||||
);
|
||||
await handler.handle(
|
||||
at(new IssueAssignedEvent('ana', 'i-1', 'p-1', 'bob', null)),
|
||||
);
|
||||
|
||||
expect(pushed.map(([endpoint]) => endpoint)).toEqual([
|
||||
'https://push.example/phone',
|
||||
'https://push.example/gone',
|
||||
]);
|
||||
expect(pushed[0][1]).toMatchObject({
|
||||
title: 'TaskStream · WEB-1',
|
||||
url: '/p/WEB/issues/WEB-1',
|
||||
});
|
||||
expect(forgotten).toEqual(['https://push.example/gone']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
import { ChangeFeed } from '../ports/change-feed';
|
||||
import { NotificationMailer } from '../ports/notification-mailer';
|
||||
import { NotificationsRepository } from '../ports/notifications.repository';
|
||||
import { PushPayload, PushSender } from '../ports/push-sender';
|
||||
import { PushSubscriptionsRepository } from '../ports/push-subscriptions.repository';
|
||||
import { UserDirectory } from '../ports/user-directory';
|
||||
import { versionOf } from '../event-handlers/read-model-notifier';
|
||||
|
||||
@@ -39,6 +41,8 @@ export class Notifier {
|
||||
private readonly changeFeed: ChangeFeed,
|
||||
private readonly mailer: NotificationMailer,
|
||||
private readonly users: UserDirectory,
|
||||
private readonly push: PushSender,
|
||||
private readonly pushSubscriptions: PushSubscriptionsRepository,
|
||||
) {}
|
||||
|
||||
async deliver(
|
||||
@@ -89,6 +93,33 @@ export class Notifier {
|
||||
if (this.mailer.enabled && delivered.length) {
|
||||
await this.email(delivered);
|
||||
}
|
||||
if (this.push.publicKey && delivered.length) {
|
||||
await this.pushToDevices(delivered);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* To every device where the person turned push on. Like e-mail, a failure
|
||||
* never blocks the event stream; a device the push service forgot is
|
||||
* forgotten here too.
|
||||
*/
|
||||
private async pushToDevices(
|
||||
notifications: NotificationReadModel[],
|
||||
): Promise<void> {
|
||||
for (const notification of notifications) {
|
||||
const devices = await this.pushSubscriptions.forUser(notification.userId);
|
||||
for (const device of devices) {
|
||||
try {
|
||||
const result = await this.push.send(device, payloadOf(notification));
|
||||
if (result === 'gone')
|
||||
await this.pushSubscriptions.forget(device.endpoint);
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Push to ${notification.userId} failed: ${(error as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A failed e-mail never blocks the event stream: it is logged and skipped. */
|
||||
@@ -116,3 +147,18 @@ export class Notifier {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What the device shows: the ticket (or project), the line and its page. */
|
||||
export function payloadOf(notification: NotificationReadModel): PushPayload {
|
||||
const project = encodeURIComponent(notification.projectKey);
|
||||
return {
|
||||
title: notification.issueKey
|
||||
? `TaskStream · ${notification.issueKey}`
|
||||
: `TaskStream · ${notification.projectKey}`,
|
||||
body: notification.summary,
|
||||
url: notification.issueKey
|
||||
? `/p/${project}/issues/${encodeURIComponent(notification.issueKey)}`
|
||||
: `/p/${project}`,
|
||||
tag: notification.id,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -28,3 +28,5 @@ export * from './outgoing-webhooks.repository';
|
||||
export * from './automations.repository';
|
||||
export * from './rate-limit.store';
|
||||
export * from './calendar-feeds.repository';
|
||||
export * from './push-sender';
|
||||
export * from './push-subscriptions.repository';
|
||||
|
||||
32
libs/api/tracker/application/src/lib/ports/push-sender.ts
Normal file
32
libs/api/tracker/application/src/lib/ports/push-sender.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
/** A browser's push subscription (Web Push), as the browser hands it over. */
|
||||
export interface PushSubscriptionRecord {
|
||||
userId: string;
|
||||
/** The push service URL of that browser on that device: unique. */
|
||||
endpoint: string;
|
||||
keys: { p256dh: string; auth: string };
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
/** What the service worker shows: a title, a line and where a tap goes. */
|
||||
export interface PushPayload {
|
||||
title: string;
|
||||
body: string;
|
||||
/** A path in the web app, e.g. `/p/WEB/issues/WEB-12`. */
|
||||
url: string;
|
||||
/** Replaces an earlier notification with the same tag on the device. */
|
||||
tag: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends Web Push messages (VAPID). Without keys configured it is off and
|
||||
* nobody is offered push.
|
||||
*/
|
||||
export abstract class PushSender {
|
||||
/** The VAPID public key browsers subscribe with; null: push is off. */
|
||||
abstract get publicKey(): string | null;
|
||||
/** `gone`: the browser dropped the subscription; forget it. */
|
||||
abstract send(
|
||||
subscription: PushSubscriptionRecord,
|
||||
payload: PushPayload,
|
||||
): Promise<'sent' | 'gone'>;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { PushSubscriptionRecord } from './push-sender';
|
||||
|
||||
/** The devices where each person turned push on. */
|
||||
export abstract class PushSubscriptionsRepository {
|
||||
abstract forUser(userId: string): Promise<PushSubscriptionRecord[]>;
|
||||
/** By endpoint: a device subscribing again replaces its entry. */
|
||||
abstract save(subscription: PushSubscriptionRecord): Promise<void>;
|
||||
/** Only the owner's: nobody drops someone else's device. */
|
||||
abstract remove(userId: string, endpoint: string): Promise<void>;
|
||||
/** The push service said it no longer exists. */
|
||||
abstract forget(endpoint: string): Promise<void>;
|
||||
}
|
||||
@@ -29,6 +29,8 @@ import {
|
||||
import {
|
||||
MarkNotificationsReadCommandHandler,
|
||||
UpdateNotificationSettingsCommandHandler,
|
||||
SubscribePushCommandHandler,
|
||||
UnsubscribePushCommandHandler,
|
||||
} from './notifications/notifications.commands';
|
||||
|
||||
import { SAVED_FILTERS } from './saved-filters/saved-filters';
|
||||
@@ -55,6 +57,8 @@ const NOTIFICATIONS = [
|
||||
GetMyNotificationSettingsQueryHandler,
|
||||
MarkNotificationsReadCommandHandler,
|
||||
UpdateNotificationSettingsCommandHandler,
|
||||
SubscribePushCommandHandler,
|
||||
UnsubscribePushCommandHandler,
|
||||
SendDueRemindersCommandHandler,
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import {
|
||||
PushSubscriptionRecord,
|
||||
PushSubscriptionsRepository,
|
||||
} from '@task-stream/api/tracker/application';
|
||||
import { Model } from 'mongoose';
|
||||
import { PushSubscriptionDoc, ReadModels } from './read-model.schemas';
|
||||
|
||||
/** Endpoints are long URLs: their hash makes a tidy, unique `id`. */
|
||||
const idOf = (endpoint: string) =>
|
||||
createHash('sha256').update(endpoint).digest('hex');
|
||||
|
||||
@Injectable()
|
||||
export class MongoPushSubscriptionsRepository extends PushSubscriptionsRepository {
|
||||
constructor(
|
||||
@InjectModel(ReadModels.PushSubscription)
|
||||
private readonly subscriptions: Model<PushSubscriptionDoc>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async forUser(userId: string): Promise<PushSubscriptionRecord[]> {
|
||||
const docs = await this.subscriptions
|
||||
.find({ userId })
|
||||
.lean<PushSubscriptionDoc[]>();
|
||||
return docs.map(({ userId: owner, endpoint, keys, createdAt }) => ({
|
||||
userId: owner,
|
||||
endpoint,
|
||||
keys,
|
||||
createdAt,
|
||||
}));
|
||||
}
|
||||
|
||||
async save(subscription: PushSubscriptionRecord): Promise<void> {
|
||||
await this.subscriptions.updateOne(
|
||||
{ id: idOf(subscription.endpoint) },
|
||||
{ $set: subscription },
|
||||
{ upsert: true },
|
||||
);
|
||||
}
|
||||
|
||||
async remove(userId: string, endpoint: string): Promise<void> {
|
||||
await this.subscriptions.deleteOne({ id: idOf(endpoint), userId });
|
||||
}
|
||||
|
||||
async forget(endpoint: string): Promise<void> {
|
||||
await this.subscriptions.deleteOne({ id: idOf(endpoint) });
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,14 @@ export interface GitIntegrationDoc {
|
||||
secret?: string;
|
||||
createdAt?: string;
|
||||
}
|
||||
export interface PushSubscriptionDoc {
|
||||
/** sha256 of the endpoint. */
|
||||
id: string;
|
||||
userId: string;
|
||||
endpoint: string;
|
||||
keys: { p256dh: string; auth: string };
|
||||
createdAt: string;
|
||||
}
|
||||
export interface CalendarFeedDoc {
|
||||
/** The user's id. */
|
||||
id: string;
|
||||
@@ -92,6 +100,7 @@ export const ReadModels = {
|
||||
Automation: 'Automation',
|
||||
AutomationRun: 'AutomationRun',
|
||||
CalendarFeed: 'CalendarFeed',
|
||||
PushSubscription: 'PushSubscription',
|
||||
} as const;
|
||||
|
||||
/*
|
||||
@@ -347,6 +356,20 @@ class CalendarFeedDocument {
|
||||
export const CalendarFeedSchema =
|
||||
SchemaFactory.createForClass(CalendarFeedDocument);
|
||||
|
||||
/** The devices where each person turned push on. */
|
||||
@Schema({ ...LOOSE, collection: 'push_subscriptions' })
|
||||
class PushSubscriptionDocument {
|
||||
/** sha256 of the endpoint. */
|
||||
@Prop({ type: String, required: true, unique: true }) id!: string;
|
||||
@Prop({ type: String, index: true }) userId!: string;
|
||||
@Prop({ type: String }) endpoint!: string;
|
||||
@Prop({ type: Object }) keys!: { p256dh: string; auth: string };
|
||||
@Prop({ type: String }) createdAt!: string;
|
||||
}
|
||||
export const PushSubscriptionSchema = SchemaFactory.createForClass(
|
||||
PushSubscriptionDocument,
|
||||
);
|
||||
|
||||
// Redeliveries happen within minutes; a month of memory is plenty.
|
||||
AutomationRunSchema.index({ at: 1 }, { expireAfterSeconds: 30 * 86_400 });
|
||||
|
||||
@@ -366,6 +389,7 @@ export const READ_MODEL_SCHEMAS = [
|
||||
{ name: ReadModels.NotificationSettings, schema: NotificationSettingsSchema },
|
||||
{ name: ReadModels.SavedFilter, schema: SavedFilterSchema },
|
||||
{ name: ReadModels.CalendarFeed, schema: CalendarFeedSchema },
|
||||
{ name: ReadModels.PushSubscription, schema: PushSubscriptionSchema },
|
||||
];
|
||||
|
||||
/** A document as the model it holds: Mongo's own `_id` left out. */
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { createECDH, randomBytes } from 'node:crypto';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import * as webpush from 'web-push';
|
||||
import { WebPushSender } from './web-push.sender';
|
||||
|
||||
// The real library, but nothing leaves the machine.
|
||||
jest.mock('web-push', () => ({
|
||||
...jest.requireActual('web-push'),
|
||||
sendNotification: jest.fn(),
|
||||
}));
|
||||
const sendNotification = webpush.sendNotification as jest.MockedFunction<
|
||||
typeof webpush.sendNotification
|
||||
>;
|
||||
|
||||
/** What a browser hands over: its P-256 public key and an auth secret. */
|
||||
function device(endpoint = 'https://push.example/abc') {
|
||||
const ecdh = createECDH('prime256v1');
|
||||
ecdh.generateKeys();
|
||||
return {
|
||||
userId: 'ana',
|
||||
endpoint,
|
||||
keys: {
|
||||
p256dh: ecdh.getPublicKey().toString('base64url'),
|
||||
auth: randomBytes(16).toString('base64url'),
|
||||
},
|
||||
createdAt: '2026-10-15T00:00:00.000Z',
|
||||
};
|
||||
}
|
||||
|
||||
const VAPID = webpush.generateVAPIDKeys();
|
||||
|
||||
function sender(withKeys = true) {
|
||||
const values: Record<string, string> = withKeys
|
||||
? {
|
||||
VAPID_PUBLIC_KEY: VAPID.publicKey,
|
||||
VAPID_PRIVATE_KEY: VAPID.privateKey,
|
||||
VAPID_SUBJECT: 'mailto:test@example.org',
|
||||
}
|
||||
: {};
|
||||
return new WebPushSender({
|
||||
get: (key: string) => values[key],
|
||||
} as unknown as ConfigService);
|
||||
}
|
||||
|
||||
const PAYLOAD = {
|
||||
title: 'TaskStream · WEB-1',
|
||||
body: 'Ana te asignó WEB-1',
|
||||
url: '/p/WEB/issues/WEB-1',
|
||||
tag: 'n-1',
|
||||
};
|
||||
|
||||
describe('WebPushSender', () => {
|
||||
afterEach(() => sendNotification.mockReset());
|
||||
|
||||
it('is off without VAPID keys, on with them', () => {
|
||||
expect(sender(false).publicKey).toBeNull();
|
||||
expect(sender().publicKey).toBe(VAPID.publicKey);
|
||||
});
|
||||
|
||||
it('builds an encrypted, VAPID-signed message for the device', () => {
|
||||
sender();
|
||||
const subscriber = device();
|
||||
const request = webpush.generateRequestDetails(
|
||||
{ endpoint: subscriber.endpoint, keys: subscriber.keys },
|
||||
JSON.stringify(PAYLOAD),
|
||||
{ TTL: 86_400 },
|
||||
);
|
||||
expect(request.headers['Content-Encoding']).toBe('aes128gcm');
|
||||
expect(String(request.headers['Authorization'])).toMatch(
|
||||
new RegExp(`^vapid t=.+, k=${VAPID.publicKey}$`),
|
||||
);
|
||||
// Encrypted: nothing of the text travels in the clear.
|
||||
expect(String(request.body)).not.toContain('WEB-1');
|
||||
});
|
||||
|
||||
it('sends the payload as JSON and keeps it a day', async () => {
|
||||
sendNotification.mockResolvedValue({
|
||||
statusCode: 201,
|
||||
body: '',
|
||||
headers: {},
|
||||
});
|
||||
expect(await sender().send(device(), PAYLOAD)).toBe('sent');
|
||||
const [target, body, options] = sendNotification.mock.calls[0];
|
||||
expect(target.endpoint).toBe('https://push.example/abc');
|
||||
expect(JSON.parse(String(body))).toEqual(PAYLOAD);
|
||||
expect(options).toMatchObject({ TTL: 86_400 });
|
||||
});
|
||||
|
||||
it('tells a subscription the push service dropped (404, 410)', async () => {
|
||||
for (const status of [404, 410]) {
|
||||
sendNotification.mockRejectedValueOnce(
|
||||
new webpush.WebPushError(
|
||||
'gone',
|
||||
status,
|
||||
{},
|
||||
'',
|
||||
'https://push.example/abc',
|
||||
),
|
||||
);
|
||||
expect(await sender().send(device(), PAYLOAD)).toBe('gone');
|
||||
}
|
||||
});
|
||||
|
||||
it('lets other failures through, to be logged', async () => {
|
||||
sendNotification.mockRejectedValue(
|
||||
new webpush.WebPushError('busy', 503, {}, '', 'https://push.example/abc'),
|
||||
);
|
||||
await expect(sender().send(device(), PAYLOAD)).rejects.toThrow('busy');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import {
|
||||
PushPayload,
|
||||
PushSender,
|
||||
PushSubscriptionRecord,
|
||||
} from '@task-stream/api/tracker/application';
|
||||
import * as webpush from 'web-push';
|
||||
|
||||
/**
|
||||
* Web Push with VAPID keys (VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY and
|
||||
* VAPID_SUBJECT, a `mailto:` or https URL the push services can reach
|
||||
* someone at). Make the keys once with `npx web-push generate-vapid-keys`;
|
||||
* changing them drops every subscription. Without them push is off.
|
||||
*/
|
||||
@Injectable()
|
||||
export class WebPushSender extends PushSender {
|
||||
private readonly logger = new Logger(WebPushSender.name);
|
||||
private readonly key: string | null;
|
||||
|
||||
constructor(config: ConfigService) {
|
||||
super();
|
||||
const publicKey = config.get<string>('VAPID_PUBLIC_KEY') || '';
|
||||
const privateKey = config.get<string>('VAPID_PRIVATE_KEY') || '';
|
||||
const subject =
|
||||
config.get<string>('VAPID_SUBJECT') || 'mailto:no-reply@pireon.dev';
|
||||
this.key = publicKey && privateKey ? publicKey : null;
|
||||
if (this.key) {
|
||||
webpush.setVapidDetails(subject, publicKey, privateKey);
|
||||
this.logger.log('Push notifications enabled');
|
||||
}
|
||||
}
|
||||
|
||||
get publicKey(): string | null {
|
||||
return this.key;
|
||||
}
|
||||
|
||||
async send(
|
||||
subscription: PushSubscriptionRecord,
|
||||
payload: PushPayload,
|
||||
): Promise<'sent' | 'gone'> {
|
||||
if (!this.key) return 'sent';
|
||||
try {
|
||||
await webpush.sendNotification(
|
||||
{ endpoint: subscription.endpoint, keys: subscription.keys },
|
||||
JSON.stringify(payload),
|
||||
// Kept a day by the push service while the device is off.
|
||||
{ TTL: 86_400, urgency: 'normal' },
|
||||
);
|
||||
return 'sent';
|
||||
} catch (error) {
|
||||
// 404 / 410: that browser dropped the subscription for good.
|
||||
if (
|
||||
error instanceof webpush.WebPushError &&
|
||||
(error.statusCode === 404 || error.statusCode === 410)
|
||||
)
|
||||
return 'gone';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
NotificationMailer,
|
||||
NotificationsRepository,
|
||||
CalendarFeedsRepository,
|
||||
PushSubscriptionsRepository,
|
||||
PushSender,
|
||||
SavedFiltersRepository,
|
||||
GitIntegrationsRepository,
|
||||
OutgoingWebhooksRepository,
|
||||
@@ -67,6 +69,8 @@ import { RedisChangeFeed } from './realtime/redis-change-feed';
|
||||
import { RedisRateLimitStore } from './redis/redis-rate-limit.store';
|
||||
import { MongoNotificationsRepository } from './mongo/notifications.repository';
|
||||
import { MongoCalendarFeedsRepository } from './mongo/calendar-feeds.repository';
|
||||
import { MongoPushSubscriptionsRepository } from './mongo/push-subscriptions.repository';
|
||||
import { WebPushSender } from './push/web-push.sender';
|
||||
import { MongoSavedFiltersRepository } from './mongo/saved-filters.repository';
|
||||
import { MongoGitIntegrationsRepository } from './mongo/git-integrations.repository';
|
||||
import { MongoOutgoingWebhooksRepository } from './mongo/outgoing-webhooks.repository';
|
||||
@@ -133,6 +137,11 @@ const PORTS = [
|
||||
// Notifications → MongoDB (per person), copies by e-mail → SMTP (optional)
|
||||
{ provide: NotificationsRepository, useClass: MongoNotificationsRepository },
|
||||
{ provide: CalendarFeedsRepository, useClass: MongoCalendarFeedsRepository },
|
||||
{
|
||||
provide: PushSubscriptionsRepository,
|
||||
useClass: MongoPushSubscriptionsRepository,
|
||||
},
|
||||
{ provide: PushSender, useClass: WebPushSender },
|
||||
{ provide: SavedFiltersRepository, useClass: MongoSavedFiltersRepository },
|
||||
{
|
||||
provide: GitIntegrationsRepository,
|
||||
|
||||
@@ -689,3 +689,14 @@ export class ProjectSettingsInput {
|
||||
@Type(() => AreaOptionInput)
|
||||
areas!: AreaOptionInput[];
|
||||
}
|
||||
|
||||
@InputType({
|
||||
description: "A browser's Web Push subscription (PushSubscription.toJSON())",
|
||||
})
|
||||
export class PushSubscriptionInput {
|
||||
@Field()
|
||||
@IsUrl({ protocols: ['https'], require_tld: false })
|
||||
endpoint!: string;
|
||||
@Field() @IsString() @MaxLength(200) p256dh!: string;
|
||||
@Field() @IsString() @MaxLength(100) auth!: string;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
NotificationGql,
|
||||
NotificationSettingsGql,
|
||||
} from './types';
|
||||
import { PushSubscriptionInput } from './inputs';
|
||||
|
||||
/** The signed-in person's notifications. */
|
||||
@Resolver(() => NotificationGql)
|
||||
@@ -40,6 +41,27 @@ export class NotificationResolver {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Mutation(() => Boolean, { description: 'Push on this device' })
|
||||
async subscribePush(
|
||||
@CurrentUser() me: User,
|
||||
@Args('subscription') subscription: PushSubscriptionInput,
|
||||
) {
|
||||
await this.notifications.subscribePush(me.id, subscription.endpoint, {
|
||||
p256dh: subscription.p256dh,
|
||||
auth: subscription.auth,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
@Mutation(() => Boolean, { description: 'Push off on this device' })
|
||||
async unsubscribePush(
|
||||
@CurrentUser() me: User,
|
||||
@Args('endpoint') endpoint: string,
|
||||
) {
|
||||
await this.notifications.unsubscribePush(me.id, endpoint);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Mutation(() => NotificationSettingsGql)
|
||||
updateNotificationSettings(
|
||||
@CurrentUser() me: User,
|
||||
|
||||
@@ -642,6 +642,12 @@ export class NotificationSettingsGql {
|
||||
description: 'Whether this installation can send e-mail at all',
|
||||
})
|
||||
emailAvailable!: boolean;
|
||||
@Field(() => String, {
|
||||
nullable: true,
|
||||
description:
|
||||
'VAPID public key to subscribe a device to push with; null: no push here',
|
||||
})
|
||||
pushPublicKey!: string | null;
|
||||
}
|
||||
|
||||
@ObjectType('CommandResult', {
|
||||
|
||||
@@ -1212,6 +1212,31 @@ export class NotificationSettingsDto {
|
||||
email!: boolean;
|
||||
}
|
||||
|
||||
export class PushSubscriptionDto {
|
||||
@ApiProperty({
|
||||
description: 'The push service URL (PushSubscription.endpoint)',
|
||||
})
|
||||
@IsUrl({ protocols: ['https'], require_tld: false })
|
||||
endpoint!: string;
|
||||
|
||||
@ApiProperty({ description: 'keys.p256dh of the subscription' })
|
||||
@IsString()
|
||||
@MaxLength(200)
|
||||
p256dh!: string;
|
||||
|
||||
@ApiProperty({ description: 'keys.auth of the subscription' })
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
auth!: string;
|
||||
}
|
||||
|
||||
export class PushEndpointDto {
|
||||
@ApiProperty({ description: 'The endpoint of the device to turn off' })
|
||||
@IsString()
|
||||
@MaxLength(2000)
|
||||
endpoint!: string;
|
||||
}
|
||||
|
||||
// ---- Git --------------------------------------------------------------------
|
||||
|
||||
export class AddGitRepositoryDto {
|
||||
|
||||
@@ -844,4 +844,11 @@ export class NotificationSettingsResponseDto {
|
||||
@ApiProperty({ description: 'Copies by e-mail' }) email!: boolean;
|
||||
@ApiProperty({ description: 'Whether this installation can send e-mail' })
|
||||
emailAvailable!: boolean;
|
||||
@ApiProperty({
|
||||
type: String,
|
||||
nullable: true,
|
||||
description:
|
||||
'VAPID public key to subscribe a device to push with; null: no push here',
|
||||
})
|
||||
pushPublicKey!: string | null;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,19 @@
|
||||
import { Body, Controller, Get, Post, Put, Query } from '@nestjs/common';
|
||||
import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpCode,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
ApiNoContentResponse,
|
||||
ApiOkResponse,
|
||||
ApiOperation,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { User } from '@task-stream/api/identity/domain';
|
||||
import {
|
||||
ApiPireonAuth,
|
||||
@@ -14,6 +28,8 @@ import {
|
||||
MarkNotificationsReadDto,
|
||||
MyNotificationsQueryDto,
|
||||
NotificationSettingsDto,
|
||||
PushEndpointDto,
|
||||
PushSubscriptionDto,
|
||||
} from './dto/requests.dto';
|
||||
import {
|
||||
MyNotificationsDto,
|
||||
@@ -67,4 +83,32 @@ export class NotificationsController {
|
||||
) {
|
||||
return this.notifications.updateSettings(me.id, body);
|
||||
}
|
||||
|
||||
@Post('push-subscriptions')
|
||||
@HttpCode(204)
|
||||
@ApiOperation({
|
||||
summary: "Push on this device (a browser's Web Push subscription)",
|
||||
})
|
||||
@ApiNoContentResponse()
|
||||
@ApiCommandErrors()
|
||||
async subscribePush(
|
||||
@CurrentUser() me: User,
|
||||
@Body() body: PushSubscriptionDto,
|
||||
): Promise<void> {
|
||||
await this.notifications.subscribePush(me.id, body.endpoint, {
|
||||
p256dh: body.p256dh,
|
||||
auth: body.auth,
|
||||
});
|
||||
}
|
||||
|
||||
@Delete('push-subscriptions')
|
||||
@HttpCode(204)
|
||||
@ApiOperation({ summary: 'Push off on this device' })
|
||||
@ApiNoContentResponse()
|
||||
async unsubscribePush(
|
||||
@CurrentUser() me: User,
|
||||
@Body() body: PushEndpointDto,
|
||||
): Promise<void> {
|
||||
await this.notifications.unsubscribePush(me.id, body.endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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