push notificaitons

This commit is contained in:
toni
2026-03-16 00:46:30 +01:00
parent 2620538a2c
commit e3184be911
20 changed files with 237 additions and 253 deletions
@@ -2,7 +2,6 @@ import express from "express";
import {
Controller,
Get,
Post,
Request,
Route,
Security,
@@ -17,13 +16,6 @@ import { KC_SECURITY_NAME } from "../services/keycloak/user/keycloak-user.js";
export class FoundEventsController extends Controller {
private readonly foundEventsService = inject(FoundEventsService);
@Post("crawl")
@Security(KC_SECURITY_NAME)
@SuccessResponse("200", "OK")
public async crawl(): Promise<void> {
await this.foundEventsService.crawl();
}
@Get("future")
@Security(KC_SECURITY_NAME)
@SuccessResponse("200", "OK")
+2 -28
View File
@@ -32,39 +32,13 @@ export class PushContoller extends Controller {
);
}
@Post("reset")
@Security(KC_SECURITY_NAME)
@SuccessResponse("200", "OK")
public async resetSubscriptions(
@Request() request: express.Request,
): Promise<void> {
return await this.pushService.reset(request);
}
@Post("clearSingle")
@Security(KC_SECURITY_NAME)
@SuccessResponse("200", "OK")
public async clearSubscription(
@Request() request: express.Request,
@Query() clientId: string,
@Query() clientId?: string,
): Promise<void> {
await this.pushService.clearSubscription(clientId, request);
}
//TODO remove
@Post("test-publish")
@Security(KC_SECURITY_NAME)
@SuccessResponse("200", "OK")
public async publishTestMessage(
@Request() request: express.Request,
): Promise<void> {
this.pushService.sendtestNotification(request);
}
//TODO remove
@Post("notify")
@SuccessResponse("200", "OK")
public async notifyEvents(): Promise<void> {
await this.pushService.sendEventNotifications();
await this.pushService.clearSubscription(clientId ?? null, request);
}
}
@@ -0,0 +1,26 @@
import { Controller, Post, Route, Security, SuccessResponse } from "tsoa";
import { Claim } from "../dtos/claim.js";
import { inject } from "../infrastructure/di/index.js";
import { FoundEventsService } from "../services/foundEvents/foundEventsService.js";
import { KC_SECURITY_NAME } from "../services/keycloak/user/keycloak-user.js";
import { PushService } from "../services/push/pushService.js";
@Route("test")
export class TestContoller extends Controller {
private readonly pushService = inject(PushService);
private readonly foundEventsService = inject(FoundEventsService);
@Post("notify")
@Security(KC_SECURITY_NAME, [Claim.UserAdmin])
@SuccessResponse("200", "OK")
public async notifyEvents(): Promise<void> {
await this.pushService.sendEventNotifications();
}
@Post("crawl")
@Security(KC_SECURITY_NAME)
@SuccessResponse("200", "OK")
public async crawl(): Promise<void> {
await this.foundEventsService.crawl();
}
}
+45 -2
View File
@@ -1,5 +1,6 @@
import constants from "constants";
import cors from "cors";
import { CronJob } from "cron";
import express, {
type NextFunction,
type Request,
@@ -11,7 +12,9 @@ import { RegisterRoutes } from "./generated/routes.js";
import { inject } from "./infrastructure/di/injector.js";
import { sessionHandler } from "./infrastructure/sessionHandler.js";
import { EnvironmentService } from "./services/environmentService.js";
import { FoundEventsService } from "./services/foundEvents/foundEventsService.js";
import { KeycloakUser } from "./services/keycloak/user/keycloak-user.js";
import { PushService } from "./services/push/pushService.js";
// import helmet from "helmet";
// TODO import http2 from 'http2';
@@ -67,12 +70,13 @@ async function run() {
// key = fs.readFileSync("src/key.pem");
port = 3000;
app.listen(port, error => {
const server = app.listen(port, error => {
if (error) {
console.error("Startup crashed:", error);
}
console.log(`Server is running at http://localhost:${port}`);
});
server.on("close", () => stopCron());
} else {
port = 5443;
const SSL_CERT_PATH = process.env["SSL_CERT_PATH"];
@@ -100,17 +104,56 @@ async function run() {
constants.SSL_OP_NO_SSLv2 |
constants.SSL_OP_NO_SSLv3,
};
https.createServer(sslOptions, app).listen(port, () => {
const server = https.createServer(sslOptions, app).listen(port, () => {
console.log(`Server is running on port ${port}`);
});
server.on("close", () => stopCron());
}
// const h2SslOptions={};
// http2.createServer(h2SslOptions, app).listen(port, ()=>{
// console.log(`HTTP/2 server is running on port ${port}`);
// })
initJobs();
startCron();
console.log("setup done");
}
const jobs: CronJob[] = [];
function initJobs() {
const eventsService = inject(FoundEventsService);
const crawlJob = CronJob.from({
cronTime: "35 4 * * *",
onTick: async () => {
await eventsService.crawl();
},
});
jobs.push(crawlJob);
const pushService = inject(PushService);
const notifyJob = CronJob.from({
cronTime: "10 12 * * *",
onTick: async () => {
await pushService.sendEventNotifications();
},
});
jobs.push(notifyJob);
}
function startCron() {
console.log("starting jobs");
for (const job of jobs) {
job.start();
}
}
async function stopCron() {
console.log("stopping jobs");
for (const job of jobs) {
job.stop();
}
}
run();
@@ -22,7 +22,7 @@ export class FoundEventsService {
maxRequestsPerMinute: 100,
maxConcurrency: 2,
requestHandler: async ({ request, page, log }) => {
if (request.retryCount > 0) return;
// if (request.retryCount > 0) return;
const label = request.label;
@@ -67,8 +67,8 @@ export async function parseTUSDetail(
const aboluteUrl =
url != null
? isAbsolute
? new URL(url)
: new URL(url, pageUrl)
? new URL(url).toString()
: new URL(url, pageUrl).toString()
: "";
return {
url: aboluteUrl,
+58 -137
View File
@@ -134,164 +134,85 @@ export class PushService {
lang: "de-DE",
// TODO renotify: true, re-enable when tag
requireInteraction: true,
timestamp: date?.valueOf(),
// timestamp: date?.valueOf(),
vibrate: [100],
// TODO tag: Topic.EVENTS, implement grouping in Angular SW
},
};
for (const subscription of subscriptions) {
if (
subscription.lastNotified &&
subscription.lastNotified >= event.foundDate
) {
for (const s of subscriptions) {
if (s.lastNotified && s.lastNotified >= event.foundDate) {
// this subscription has already seen this event
continue;
}
if (
!this.eventMatchesFilter(
event,
subscription.topicConfiguration,
)
) {
if (!this.eventMatchesFilter(event, s.topicConfiguration)) {
// this subscription does not care for this event
continue;
}
console.log(`sending ${subscriptions.length} test messages`);
for (const s of subscriptions) {
try {
let backoff = 500;
let retry: boolean;
do {
console.log("SENDING");
console.dir("payload");
retry = await this.sendNotification(
s,
payload,
backoff,
);
backoff *= 2;
} while (retry);
} catch (error) {
console.error("Cannot send notification: ", error);
throw error;
}
try {
let backoff = 500;
let retry: boolean;
let maxRetry = 5;
do {
retry = await this.sendNotification(
s,
payload,
backoff,
);
if (maxRetry <= 0) {
throw new Error("Exceeded max retry");
}
backoff *= 2;
maxRetry--;
} while (retry);
await this.db.doRequest(
async prisma =>
prisma.pushSubscription.update({
where: {
id: s.id,
},
data: {
lastNotified: new Date(Date.now()),
},
}),
null,
);
} catch (error) {
console.error("Cannot send notification: ", error);
// throw error;
}
}
}
await this.db.doRequest(
async prisma =>
prisma.pushSubscription.updateMany({
where: {
id: {
in: subscriptions.map(s => s.id),
},
},
data: {
lastNotified: new Date(Date.now()),
},
}),
null,
);
}
public async sendtestNotification(request: Request) {
const subscriptions = await this.db.doRequest(
async prisma =>
prisma.pushSubscription.findMany({ where: { topic: "TEST" } }),
request,
);
const payload: AngularPushPayload = {
notification: {
title: "ATitle",
actions: [
{
action: "explode",
title: "Make Boom",
},
],
body: "DatBod",
data: {
onActionClick: {
default: {
operation: NotificationActionOperation.OPEN_WINDOW,
},
explode: {
operation: NotificationActionOperation.OPEN_WINDOW,
url: "explode.html",
},
},
},
icon: "https://taekwondo-chemnitz.toni714.de/favicon.ico",
lang: "de-DE",
renotify: true,
requireInteraction: true,
tag: "group-tag",
timestamp: Date.now(),
vibrate: [100, 50, 100],
},
};
console.log(`sending ${subscriptions.length} test messages`);
for (const s of subscriptions) {
const subscription: webpush.PushSubscription = {
endpoint: s.endpoint,
keys: {
auth: s.auth,
p256dh: s.p256dh,
},
expirationTime: s.expirationTime,
};
try {
const result = await webpush.sendNotification(
subscription,
JSON.stringify(payload),
{
topic: Topic.TEST,
},
);
console.log("success");
console.dir(result);
} catch (error) {
console.error("Cannot send notification: ", error);
throw error;
}
}
}
public async reset(request: Request): Promise<void> {
const userId = await this.userService.getUid(request, request.res);
const subscriptions = await this.db.doRequest(
async prisma =>
await prisma.pushSubscription.deleteMany({
where: { userId: userId },
}),
request,
);
console.log(`deleted ${subscriptions.count} subs for ${userId}`);
}
public async clearSubscription(
clientId: string,
clientId: string | null,
request: Request,
): Promise<number> {
const userId = await this.userService.getUid(request, request.res);
const batchResult = await this.db.doRequest(
async prisma =>
await prisma.pushSubscription.deleteMany({
where: {
userId: userId,
AND: {
clientId: clientId,
},
},
}),
request,
);
const batchResult = clientId
? await this.db.doRequest(
async prisma =>
await prisma.pushSubscription.deleteMany({
where: {
userId: userId,
AND: {
clientId: clientId,
},
},
}),
request,
)
: await this.db.doRequest(
async prisma =>
await prisma.pushSubscription.deleteMany({
where: {
userId: userId,
},
}),
request,
);
return batchResult.count;
}