Browse Source

Merge branch 'master' into feature/admin-panel

Christian Kahlau 3 years ago
parent
commit
f178e1379a
54 changed files with 1403 additions and 47 deletions
  1. 7 1
      .gitignore
  2. 2 2
      .gitmodules
  3. 8 0
      Readme.md
  4. 0 0
      bootstrap-theme
  5. 3 1
      common/defaults.module.ts
  6. 2 0
      common/types/http-check-config.d.ts
  7. 3 0
      fcm/express/.env.default
  8. 24 0
      fcm/express/package.json
  9. 109 0
      fcm/express/src/index.ts
  10. 16 0
      fcm/express/tsconfig.json
  11. 129 0
      fcm/install/install.sh
  12. 16 0
      fcm/ng/.browserslistrc
  13. 16 0
      fcm/ng/.editorconfig
  14. 42 0
      fcm/ng/.gitignore
  15. 4 0
      fcm/ng/.vscode/extensions.json
  16. 20 0
      fcm/ng/.vscode/launch.json
  17. 42 0
      fcm/ng/.vscode/tasks.json
  18. 27 0
      fcm/ng/README.md
  19. 100 0
      fcm/ng/angular.json
  20. 44 0
      fcm/ng/karma.conf.js
  21. 39 0
      fcm/ng/package.json
  22. 9 0
      fcm/ng/proxy-conf.json
  23. 45 0
      fcm/ng/src/app/app.component.html
  24. 0 0
      fcm/ng/src/app/app.component.scss
  25. 23 0
      fcm/ng/src/app/app.component.spec.ts
  26. 51 0
      fcm/ng/src/app/app.component.ts
  27. 13 0
      fcm/ng/src/app/app.module.ts
  28. 16 0
      fcm/ng/src/app/services/firebase.service.spec.ts
  29. 90 0
      fcm/ng/src/app/services/firebase.service.ts
  30. 0 0
      fcm/ng/src/assets/.gitkeep
  31. 4 0
      fcm/ng/src/environments/environment.prod.ts
  32. 17 0
      fcm/ng/src/environments/environment.ts
  33. BIN
      fcm/ng/src/favicon.ico
  34. 5 0
      fcm/ng/src/firebase-messaging-sw.js
  35. 13 0
      fcm/ng/src/index.html
  36. 12 0
      fcm/ng/src/main.ts
  37. 53 0
      fcm/ng/src/polyfills.ts
  38. 21 0
      fcm/ng/src/styles.scss
  39. 26 0
      fcm/ng/src/test.ts
  40. 15 0
      fcm/ng/tsconfig.app.json
  41. 32 0
      fcm/ng/tsconfig.json
  42. 18 0
      fcm/ng/tsconfig.spec.json
  43. 1 1
      ng/angular.json
  44. 1 1
      ng/src/styles.scss
  45. 3 1
      server/.env.default
  46. 34 1
      server/docs/Monitoring.postman_collection.json
  47. 15 1
      server/install/install.sh
  48. 1 0
      server/package.json
  49. 107 20
      server/src/ctrl/database.class.ts
  50. 48 0
      server/src/ctrl/fcm-controller.class.ts
  51. 40 18
      server/src/ctrl/http-check-controller.class.ts
  52. 7 0
      server/src/migrations/202212301910_website_healthcheck_notification_defaults.sql
  53. 27 0
      server/src/webhdl/fcm-api-handler.class.ts
  54. 3 0
      server/src/webserver.class.ts

+ 7 - 1
.gitignore

@@ -1,3 +1,4 @@
+/.idea/
 node_modules/
 package-lock.json
 
@@ -5,8 +6,13 @@ daemon/data/
 daemon/dist/
 daemon/.env
 
+server/google-cloud/
 server/public/
 server/dist/
 server/data/
 server/.env
-/.idea/
+
+fcm/express/google-cloud/
+fcm/express/dist/
+fcm/express/public/
+fcm/express/.env

+ 2 - 2
.gitmodules

@@ -1,4 +1,4 @@
-[submodule "ng/bootstrap-theme"]
-	path = ng/bootstrap-theme
+[submodule "bootstrap-theme"]
+	path = bootstrap-theme
 	url = https://gogs.hostbbq.com/hostbbq/bootstrap-theme.git
 	branch = master

+ 8 - 0
Readme.md

@@ -15,3 +15,11 @@ curl -fsSL https://gogs.hostbbq.com/hostbbq/hostbbq-monitoring/raw/master/daemon
 ```bash
 curl -fsSL https://gogs.hostbbq.com/hostbbq/hostbbq-monitoring/raw/master/server/install/install.sh | sudo -E bash -
 ```
+
+## HostBBQ FCM Registration Service
+
+### Install
+
+```bash
+curl -fsSL https://gogs.hostbbq.com/hostbbq/hostbbq-monitoring/raw/master/fcm/install/install.sh | sudo -E bash -
+```

+ 0 - 0
ng/bootstrap-theme → bootstrap-theme


+ 3 - 1
common/defaults.module.ts

@@ -5,7 +5,9 @@ export const serverSync = {
 export const serviceChecks = {
   active: true,
   httpTimeout: 10000,
-  interval: 300
+  interval: 300,
+  notify: false,
+  notifyThreshold: 3
 };
 
 export default {

+ 2 - 0
common/types/http-check-config.d.ts

@@ -7,5 +7,7 @@ type HttpCheckConfig = {
   active: boolean;
   interval: number;
   timeout?: number;
+  notify: boolean;
+  notifyThreshold: number;
   checks: string[];
 };

+ 3 - 0
fcm/express/.env.default

@@ -0,0 +1,3 @@
+GOOGLE_APPLICATION_CREDENTIALS="google-cloud/firebase-adminsdk.json"
+GOOGLE_GLOUD_MESSAGING_CREDENTIALS="google-cloud/gcm-api.json"
+WEB_PORT=8888

+ 24 - 0
fcm/express/package.json

@@ -0,0 +1,24 @@
+{
+  "name": "express-fcm",
+  "version": "1.0.0",
+  "description": "",
+  "main": "dist/index.js",
+  "scripts": {
+    "start": "node .",
+    "start:dev:local": "npm run build && npm run start",
+    "build": "tsc -b"
+  },
+  "author": "Christian Kahlau, HostBBQ ©2023",
+  "license": "ISC",
+  "dependencies": {
+    "axios": "^1.2.2",
+    "dotenv": "^16.0.3",
+    "express": "^4.18.2",
+    "firebase-admin": "^11.4.1"
+  },
+  "devDependencies": {
+    "@types/express": "^4.17.15",
+    "@types/node": "^18.11.18",
+    "typescript": "^4.9.4"
+  }
+}

+ 109 - 0
fcm/express/src/index.ts

@@ -0,0 +1,109 @@
+import axios, { AxiosResponse, AxiosError } from 'axios';
+import dotenv from 'dotenv';
+import express, { NextFunction, Request, Response } from 'express';
+import firebaseAdmin from 'firebase-admin';
+import fsp from 'fs/promises';
+import path from 'path';
+
+dotenv.config();
+
+const STATIC_WEB_DIR = 'public';
+
+(async () => {
+  try {
+    const gcmSettings = JSON.parse(
+      await fsp.readFile(process.env.GOOGLE_GLOUD_MESSAGING_CREDENTIALS ?? 'google-cloud/gcm-api.json', { encoding: 'utf-8' })
+    );
+
+    const server = express();
+    const firebase = firebaseAdmin.initializeApp();
+
+    server.get('/topics/:regToken', async (req, res, next) => {
+      try {
+        const regToken = req.params.regToken;
+        const { apiToken } = gcmSettings;
+        const response = await axios.get<any, AxiosResponse<any>>(`https://iid.googleapis.com/iid/info/${regToken}?details=true`, {
+          headers: {
+            Authorization: `key=${apiToken}`
+          }
+        });
+        res.send(response.data);
+      } catch (err) {
+        next(err);
+      }
+    });
+
+    server.put('/topics/:topic/:regToken', async (req, res, next) => {
+      try {
+        const topic = req.params.topic;
+        const regToken = req.params.regToken;
+
+        const response = await firebase.messaging().subscribeToTopic(regToken, topic);
+        if (!response.failureCount) return res.send({ ok: true });
+
+        throw response.errors;
+      } catch (err) {
+        next(err);
+      }
+    });
+
+    server.delete('/topics/:topic/:regToken', async (req, res, next) => {
+      try {
+        const topic = req.params.topic;
+        const regToken = req.params.regToken;
+
+        const response = await firebase.messaging().unsubscribeFromTopic(regToken, topic);
+        if (!response.failureCount) return res.send({ ok: true });
+
+        throw response.errors;
+      } catch (err) {
+        next(err);
+      }
+    });
+
+    server.get('/logo.png', async (req, res, next) => {
+      try {
+        const files = await fsp.readdir(STATIC_WEB_DIR, { encoding: 'utf-8' });
+        const logo = files.find(file => file.includes('logo') && file.endsWith('.png'));
+
+        if (!logo) {
+          throw { type: 'http', message: 'File not found', status: 404 };
+        }
+
+        res.sendFile(path.resolve(STATIC_WEB_DIR, logo));
+      } catch (err) {
+        next(err);
+      }
+    });
+
+    server.use('/', express.static(STATIC_WEB_DIR));
+
+    server.use('**', express.static(path.join(STATIC_WEB_DIR, 'index.html')));
+
+    server.use((err: any, req: Request, res: Response, next: NextFunction) => {
+      let log = false;
+
+      if (err instanceof AxiosError) {
+        log = true;
+        res.status(err.status ?? err.response?.status ?? 500).send(err.message);
+      } else {
+        const keys = Object.keys(err);
+
+        if (keys.includes('type') && err.type === 'http') {
+          res.status(err.status).send(err.message);
+        } else {
+          log = true;
+          res.status(500).send(JSON.stringify(err));
+        }
+      }
+
+      if (log) console.error('[ERROR] Webservice ErrorHandler caught:', err);
+    });
+
+    const port = Number(process.env.WEB_PORT ?? '80');
+    server.listen(port, () => console.log('[FCM BACKEND] Webserver running at', `http://localhost:${port}`));
+  } catch (err) {
+    console.error(err);
+    process.exit(1);
+  }
+})();

+ 16 - 0
fcm/express/tsconfig.json

@@ -0,0 +1,16 @@
+{
+  "compilerOptions": {
+    "strict": true,
+    "outDir": "./dist",
+    "esModuleInterop": true,
+    "moduleResolution": "node",
+    "module": "CommonJS",
+    "target": "ES2016",
+    "sourceMap": true,
+    "baseUrl": "./src",
+    "paths": {
+      "*": ["node_modules/*", "src/*"]
+    }
+  },
+  "include": ["./src/*", "./src/**/*"]
+}

+ 129 - 0
fcm/install/install.sh

@@ -0,0 +1,129 @@
+#!/bin/bash
+
+INSTALL_DIR="${PWD}"
+
+# Check system requirements: Git, Node & NPM
+EXC_GIT="$(/usr/bin/which git)"
+if [ -z "$EXC_GIT" ]; then
+  echo "[ERROR] Missing required system dependency 'git'." >&2
+  echo "Please install using \"apt install git\"" >&2
+  exit 1
+fi
+
+EXC_NPM="$(/usr/bin/which npm)"
+if [ -z "$EXC_NPM" ]; then
+  echo "[ERROR] Missing required system dependency 'npm'." >&2
+  echo "Please install following the official install documentation." >&2
+  exit 1
+fi
+
+EXC_NODE="$(/usr/bin/which node)"
+if [ -z "$EXC_NODE" ]; then
+  echo "[ERROR] Missing required system dependency 'node'." >&2
+  echo "Please install following the official install documentation." >&2
+  exit 1
+fi
+
+GCC_CONFIG_DIR="${INSTALL_DIR}/google-cloud"
+FCM_ACCOUNT_JSON="${GCC_CONFIG_DIR}/firebase-adminsdk.json"
+GCM_API_JSON="${GCC_CONFIG_DIR}/gcm-api.json"
+
+if [ ! -d "$GCC_CONFIG_DIR" ]; then
+  echo "[ERROR] Missing required google cloud key files. Please prepare directory 'google-cloud' in install directory." >&2
+  exit 1
+fi
+
+if [ ! -f "$FCM_ACCOUNT_JSON" ]; then
+  echo "[ERROR] Missing required Firebase Admin SDK key file. Please provide this file as 'google-cloud/firebase-adminsdk.json' in order to install." >&2
+  exit 1
+fi
+
+if [ ! -f "$GCM_API_JSON" ]; then
+  echo "[ERROR] Missing required Google Cloud API key file. Please provide this file as 'google-cloud/gcm-api.json' in order to install." >&2
+  exit 1
+fi
+
+# exit on error exit codes
+set -e
+
+TMPFOLDER="/tmp/hbbq/monitoring/$(date +'%Y%m%d%H%M%S')"
+
+echo "[INSTALL] Cloning entire project into temp folder $TMPFOLDER"
+mkdir -p "$TMPFOLDER"
+git clone https://gogs.hostbbq.com/hostbbq/hostbbq-monitoring.git "$TMPFOLDER"
+
+cd "$TMPFOLDER"
+
+echo "[INSTALL] Cloning submodules ..."
+git submodule init
+git submodule update
+
+cd "$TMPFOLDER/fcm/express"
+echo "[INSTALL] Installing npm build dependencies for FCM backend API project"
+$EXC_NPM install
+
+cd "$TMPFOLDER/fcm/ng"
+echo "[INSTALL] Installing npm build dependencies for FCM Angular frontend project"
+$EXC_NPM install
+
+echo "[INSTALL] Building FCM Angular frontend project"
+$EXC_NPM run build
+
+cd "$TMPFOLDER/fcm/express"
+echo "[INSTALL] Transpiling typescript sources of FCM backend API project"
+$EXC_NPM run build
+
+echo "[INSTALL] Installing server application"
+if [ -d "$INSTALL_DIR/dist" ]; then
+  rm -rf "$INSTALL_DIR/dist"
+fi
+cp -rv "dist" "$INSTALL_DIR/"
+if [ -d "$INSTALL_DIR/public" ]; then
+  rm -rf "$INSTALL_DIR/public"
+fi
+cp -rv "public" "$INSTALL_DIR/"
+if [ ! -f "$INSTALL_DIR/.env" ]; then
+  cp -v ".env.default" "$INSTALL_DIR/.env"
+fi
+cp -v "package.json" "$INSTALL_DIR/"
+
+cd "$INSTALL_DIR"
+
+echo "[INSTALL] Installing npm runtime dependencies"
+$EXC_NPM install --omit=dev
+
+echo "[INSTALL] Creating and enabling systemd unit \"monitoring@fcm.service\""
+SVC_FILE="/lib/systemd/system/monitoring@fcm.service"
+
+ACTION="update"
+if [ ! -f "$SVC_FILE" ]; then
+  ACTION="install"
+fi
+
+cat > $SVC_FILE << EOF
+[Unit]
+Description=HostBBQ FCM Registration Service
+After=network.target
+
+[Service]
+Type=simple
+WorkingDirectory=$INSTALL_DIR
+ExecStart=node .
+
+[Install]
+WantedBy=multi-user.target
+Alias=monitoring@fcm.service
+EOF
+
+if [[ "$ACTION" = "install" ]]; then
+  systemctl enable monitoring@fcm.service
+  systemctl start monitoring@fcm.service
+else
+  systemctl daemon-reload
+  systemctl restart monitoring@fcm.service
+fi
+
+echo "[CLEANUP] Removing temp folder $TMPFOLDER"
+rm -rf "$TMPFOLDER"
+
+echo "[SUCCESS] HostBBQ FCM Registration Service installed and activated successfully"

+ 16 - 0
fcm/ng/.browserslistrc

@@ -0,0 +1,16 @@
+# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
+# For additional information regarding the format and rule options, please see:
+# https://github.com/browserslist/browserslist#queries
+
+# For the full list of supported browsers by the Angular framework, please see:
+# https://angular.io/guide/browser-support
+
+# You can see what browsers were selected by your queries by running:
+#   npx browserslist
+
+last 1 Chrome version
+last 1 Firefox version
+last 2 Edge major versions
+last 2 Safari major versions
+last 2 iOS major versions
+Firefox ESR

+ 16 - 0
fcm/ng/.editorconfig

@@ -0,0 +1,16 @@
+# Editor configuration, see https://editorconfig.org
+root = true
+
+[*]
+charset = utf-8
+indent_style = space
+indent_size = 2
+insert_final_newline = true
+trim_trailing_whitespace = true
+
+[*.ts]
+quote_type = single
+
+[*.md]
+max_line_length = off
+trim_trailing_whitespace = false

+ 42 - 0
fcm/ng/.gitignore

@@ -0,0 +1,42 @@
+# See http://help.github.com/ignore-files/ for more about ignoring files.
+
+# Compiled output
+/dist
+/tmp
+/out-tsc
+/bazel-out
+
+# Node
+/node_modules
+npm-debug.log
+yarn-error.log
+
+# IDEs and editors
+.idea/
+.project
+.classpath
+.c9/
+*.launch
+.settings/
+*.sublime-workspace
+
+# Visual Studio Code
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
+.history/*
+
+# Miscellaneous
+/.angular/cache
+.sass-cache/
+/connect.lock
+/coverage
+/libpeerconnection.log
+testem.log
+/typings
+
+# System files
+.DS_Store
+Thumbs.db

+ 4 - 0
fcm/ng/.vscode/extensions.json

@@ -0,0 +1,4 @@
+{
+  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
+  "recommendations": ["angular.ng-template"]
+}

+ 20 - 0
fcm/ng/.vscode/launch.json

@@ -0,0 +1,20 @@
+{
+  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
+  "version": "0.2.0",
+  "configurations": [
+    {
+      "name": "ng serve",
+      "type": "pwa-chrome",
+      "request": "launch",
+      "preLaunchTask": "npm: start",
+      "url": "http://localhost:4200/"
+    },
+    {
+      "name": "ng test",
+      "type": "chrome",
+      "request": "launch",
+      "preLaunchTask": "npm: test",
+      "url": "http://localhost:9876/debug.html"
+    }
+  ]
+}

+ 42 - 0
fcm/ng/.vscode/tasks.json

@@ -0,0 +1,42 @@
+{
+  // For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
+  "version": "2.0.0",
+  "tasks": [
+    {
+      "type": "npm",
+      "script": "start",
+      "isBackground": true,
+      "problemMatcher": {
+        "owner": "typescript",
+        "pattern": "$tsc",
+        "background": {
+          "activeOnStart": true,
+          "beginsPattern": {
+            "regexp": "(.*?)"
+          },
+          "endsPattern": {
+            "regexp": "bundle generation complete"
+          }
+        }
+      }
+    },
+    {
+      "type": "npm",
+      "script": "test",
+      "isBackground": true,
+      "problemMatcher": {
+        "owner": "typescript",
+        "pattern": "$tsc",
+        "background": {
+          "activeOnStart": true,
+          "beginsPattern": {
+            "regexp": "(.*?)"
+          },
+          "endsPattern": {
+            "regexp": "bundle generation complete"
+          }
+        }
+      }
+    }
+  ]
+}

+ 27 - 0
fcm/ng/README.md

@@ -0,0 +1,27 @@
+# NgFcm
+
+This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 14.2.10.
+
+## Development server
+
+Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files.
+
+## Code scaffolding
+
+Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
+
+## Build
+
+Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
+
+## Running unit tests
+
+Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
+
+## Running end-to-end tests
+
+Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities.
+
+## Further help
+
+To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page.

+ 100 - 0
fcm/ng/angular.json

@@ -0,0 +1,100 @@
+{
+  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
+  "version": 1,
+  "newProjectRoot": "projects",
+  "projects": {
+    "ng-fcm": {
+      "projectType": "application",
+      "schematics": {
+        "@schematics/angular:component": {
+          "style": "scss"
+        }
+      },
+      "root": "",
+      "sourceRoot": "src",
+      "prefix": "app",
+      "architect": {
+        "build": {
+          "builder": "@angular-devkit/build-angular:browser",
+          "options": {
+            "outputPath": "../express/public",
+            "index": "src/index.html",
+            "main": "src/main.ts",
+            "polyfills": "src/polyfills.ts",
+            "tsConfig": "tsconfig.app.json",
+            "inlineStyleLanguage": "scss",
+            "assets": ["src/favicon.ico", "src/assets", "src/firebase-messaging-sw.js"],
+            "styles": ["src/styles.scss"],
+            "scripts": ["../../bootstrap-theme/dist/js/bootstrap.js"]
+          },
+          "configurations": {
+            "production": {
+              "budgets": [
+                {
+                  "type": "initial",
+                  "maximumWarning": "500kb",
+                  "maximumError": "1mb"
+                },
+                {
+                  "type": "anyComponentStyle",
+                  "maximumWarning": "2kb",
+                  "maximumError": "4kb"
+                }
+              ],
+              "fileReplacements": [
+                {
+                  "replace": "src/environments/environment.ts",
+                  "with": "src/environments/environment.prod.ts"
+                }
+              ],
+              "outputHashing": "all"
+            },
+            "development": {
+              "buildOptimizer": false,
+              "optimization": false,
+              "vendorChunk": true,
+              "extractLicenses": false,
+              "sourceMap": true,
+              "namedChunks": true
+            }
+          },
+          "defaultConfiguration": "production"
+        },
+        "serve": {
+          "builder": "@angular-devkit/build-angular:dev-server",
+          "configurations": {
+            "production": {
+              "browserTarget": "ng-fcm:build:production"
+            },
+            "development": {
+              "browserTarget": "ng-fcm:build:development"
+            }
+          },
+          "defaultConfiguration": "development"
+        },
+        "extract-i18n": {
+          "builder": "@angular-devkit/build-angular:extract-i18n",
+          "options": {
+            "browserTarget": "ng-fcm:build"
+          }
+        },
+        "test": {
+          "builder": "@angular-devkit/build-angular:karma",
+          "options": {
+            "main": "src/test.ts",
+            "polyfills": "src/polyfills.ts",
+            "tsConfig": "tsconfig.spec.json",
+            "karmaConfig": "karma.conf.js",
+            "inlineStyleLanguage": "scss",
+            "assets": ["src/favicon.ico", "src/assets"],
+            "styles": ["src/styles.scss"],
+            "scripts": []
+          }
+        }
+      }
+    }
+  },
+  "cli": {
+    "analytics": false
+  }
+}

+ 44 - 0
fcm/ng/karma.conf.js

@@ -0,0 +1,44 @@
+// Karma configuration file, see link for more information
+// https://karma-runner.github.io/1.0/config/configuration-file.html
+
+module.exports = function (config) {
+  config.set({
+    basePath: '',
+    frameworks: ['jasmine', '@angular-devkit/build-angular'],
+    plugins: [
+      require('karma-jasmine'),
+      require('karma-chrome-launcher'),
+      require('karma-jasmine-html-reporter'),
+      require('karma-coverage'),
+      require('@angular-devkit/build-angular/plugins/karma')
+    ],
+    client: {
+      jasmine: {
+        // you can add configuration options for Jasmine here
+        // the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html
+        // for example, you can disable the random execution with `random: false`
+        // or set a specific seed with `seed: 4321`
+      },
+      clearContext: false // leave Jasmine Spec Runner output visible in browser
+    },
+    jasmineHtmlReporter: {
+      suppressAll: true // removes the duplicated traces
+    },
+    coverageReporter: {
+      dir: require('path').join(__dirname, './coverage/ng-fcm'),
+      subdir: '.',
+      reporters: [
+        { type: 'html' },
+        { type: 'text-summary' }
+      ]
+    },
+    reporters: ['progress', 'kjhtml'],
+    port: 9876,
+    colors: true,
+    logLevel: config.LOG_INFO,
+    autoWatch: true,
+    browsers: ['Chrome'],
+    singleRun: false,
+    restartOnFileChange: true
+  });
+};

+ 39 - 0
fcm/ng/package.json

@@ -0,0 +1,39 @@
+{
+  "name": "ng-fcm",
+  "version": "0.0.0",
+  "scripts": {
+    "ng": "ng",
+    "start": "ng serve --disable-host-check true --proxy-config proxy-conf.json",
+    "build": "ng build",
+    "watch": "ng build --watch --configuration development",
+    "test": "ng test"
+  },
+  "private": true,
+  "dependencies": {
+    "@angular/animations": "^14.2.0",
+    "@angular/common": "^14.2.0",
+    "@angular/compiler": "^14.2.0",
+    "@angular/core": "^14.2.0",
+    "@angular/forms": "^14.2.0",
+    "@angular/platform-browser": "^14.2.0",
+    "@angular/platform-browser-dynamic": "^14.2.0",
+    "@angular/router": "^14.2.0",
+    "firebase": "^9.15.0",
+    "rxjs": "~7.5.0",
+    "tslib": "^2.3.0",
+    "zone.js": "~0.11.4"
+  },
+  "devDependencies": {
+    "@angular-devkit/build-angular": "^14.2.10",
+    "@angular/cli": "~14.2.10",
+    "@angular/compiler-cli": "^14.2.0",
+    "@types/jasmine": "~4.0.0",
+    "jasmine-core": "~4.3.0",
+    "karma": "~6.4.0",
+    "karma-chrome-launcher": "~3.1.0",
+    "karma-coverage": "~2.2.0",
+    "karma-jasmine": "~5.1.0",
+    "karma-jasmine-html-reporter": "~2.0.0",
+    "typescript": "~4.7.2"
+  }
+}

+ 9 - 0
fcm/ng/proxy-conf.json

@@ -0,0 +1,9 @@
+[
+  {
+    "context": ["/api"],
+    "pathRewrite": {
+      "^/api": ""
+    },
+    "target": "http://localhost:3000"
+  }
+]

+ 45 - 0
fcm/ng/src/app/app.component.html

@@ -0,0 +1,45 @@
+<nav class="navbar navbar-expand-lg navbar-light container-md">
+  <div class="container-fluid bg-light">
+    <a class="navbar-brand navbar-brand-logo" href="#">HostBBQ FCM Registration Page</a>
+    <button
+      class="navbar-toggler"
+      type="button"
+      data-bs-toggle="collapse"
+      data-bs-target="#navbarSupportedContent"
+      aria-controls="navbarSupportedContent"
+      aria-expanded="false"
+      aria-label="Toggle navigation">
+      <span class="navbar-toggler-icon"></span>
+    </button>
+  </div>
+  <div class="collapse navbar-collapse justify-content-end" id="navbarSupportedContent">
+    <ul class="navbar-nav pull-right">
+      <!-- <li class="nav-item dropdown">
+        <a id="loginDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false" [routerLink]="'admin'" >Admin</a>
+      </li> -->
+    </ul>
+  </div>
+</nav>
+
+<div class="container pt-5">
+  <div class="mb-3">
+    <h4>Registration Token:</h4>
+    <input type="text" class="form-control" readonly [value]="regToken" />
+  </div>
+
+  <div class="mb-3">
+    <h4>Subscribed Topics:</h4>
+    <div *ngFor="let topic of topics; index as i" class="form-check form-switch pointer">
+      <input
+        class="form-check-input"
+        id="topic-switch-{{ i }}"
+        type="checkbox"
+        [value]="topic"
+        (change)="toggleSubscribe(topic, $event)"
+        [checked]="topic.checked" />
+      <label class="form-check-label" for="topic-switch-{{ i }}">
+        {{ topic.topic }}
+      </label>
+    </div>
+  </div>
+</div>

+ 0 - 0
fcm/ng/src/app/app.component.scss


+ 23 - 0
fcm/ng/src/app/app.component.spec.ts

@@ -0,0 +1,23 @@
+import { TestBed } from '@angular/core/testing';
+import { AppComponent } from './app.component';
+
+describe('AppComponent', () => {
+  beforeEach(async () => {
+    await TestBed.configureTestingModule({
+      declarations: [AppComponent]
+    }).compileComponents();
+  });
+
+  it('should create the app', () => {
+    const fixture = TestBed.createComponent(AppComponent);
+    const app = fixture.componentInstance;
+    expect(app).toBeTruthy();
+  });
+
+  it('should render title', () => {
+    const fixture = TestBed.createComponent(AppComponent);
+    fixture.detectChanges();
+    const compiled = fixture.nativeElement as HTMLElement;
+    expect(compiled.querySelector('.content span')?.textContent).toContain('ng-fcm app is running!');
+  });
+});

+ 51 - 0
fcm/ng/src/app/app.component.ts

@@ -0,0 +1,51 @@
+import { Component, OnInit } from '@angular/core';
+import { FirebaseService } from './services/firebase.service';
+
+type TopicCheckOption = { topic: string; checked: boolean };
+
+@Component({
+  selector: 'app-root',
+  templateUrl: './app.component.html',
+  styleUrls: ['./app.component.scss']
+})
+export class AppComponent implements OnInit {
+  public regToken: string = '';
+  public topics: TopicCheckOption[] = [];
+
+  constructor(public firebase: FirebaseService) {}
+
+  async ngOnInit() {
+    try {
+      await this.firebase.requestPermission();
+
+      console.log('✅ Notification permissions granted');
+
+      this.regToken = await this.firebase.getRegistrationToken();
+      console.log('✅ Registration Token:', this.regToken);
+
+      const iidInfo = await this.firebase.getInstanceInfo();
+      const subscribedTo = Object.keys(iidInfo.rel?.topics ?? {});
+
+      this.topics = this.firebase.topics.map(topic => ({ topic, checked: subscribedTo.includes(topic) }));
+    } catch (err) {
+      console.error(err);
+    }
+  }
+
+  async toggleSubscribe(topic: TopicCheckOption, event: Event) {
+    try {
+      const checked = (event.target as HTMLInputElement).checked;
+      console.log('[CHECKED]', topic, checked);
+
+      if (checked) {
+        await this.firebase.subscribeToTopic(topic.topic);
+      } else {
+        await this.firebase.unsubscribeFromTopic(topic.topic);
+      }
+
+      topic.checked = checked;
+    } catch (err) {
+      console.error(err);
+    }
+  }
+}

+ 13 - 0
fcm/ng/src/app/app.module.ts

@@ -0,0 +1,13 @@
+import { HttpClientModule } from '@angular/common/http';
+import { NgModule } from '@angular/core';
+import { BrowserModule } from '@angular/platform-browser';
+
+import { AppComponent } from './app.component';
+
+@NgModule({
+  declarations: [AppComponent],
+  imports: [BrowserModule, HttpClientModule],
+  providers: [],
+  bootstrap: [AppComponent]
+})
+export class AppModule {}

+ 16 - 0
fcm/ng/src/app/services/firebase.service.spec.ts

@@ -0,0 +1,16 @@
+import { TestBed } from '@angular/core/testing';
+
+import { FirebaseService } from './firebase.service';
+
+describe('FirebaseService', () => {
+  let service: FirebaseService;
+
+  beforeEach(() => {
+    TestBed.configureTestingModule({});
+    service = TestBed.inject(FirebaseService);
+  });
+
+  it('should be created', () => {
+    expect(service).toBeTruthy();
+  });
+});

+ 90 - 0
fcm/ng/src/app/services/firebase.service.ts

@@ -0,0 +1,90 @@
+import { HttpClient } from '@angular/common/http';
+import { Injectable } from '@angular/core';
+import { Analytics, getAnalytics } from 'firebase/analytics';
+import { FirebaseApp, initializeApp } from 'firebase/app';
+import { getMessaging, getToken, Messaging } from 'firebase/messaging';
+import { firstValueFrom, tap } from 'rxjs';
+import { environment } from 'src/environments/environment';
+
+type FirebaseInstanceInformation = {
+  application: string;
+  authorizedEntity: string;
+  gmiRegistrationId: string;
+  platform: string;
+  rel?: {
+    topics?: {
+      [topic: string]: { addDate: string };
+    };
+  };
+  scope: string;
+  subtype: string;
+};
+
+const firebaseConfig = {
+  apiKey: 'AIzaSyArRPxVjypXPXctcuafmwT6DZiElXtnj9g',
+  authDomain: 'hostbbq-fcm-notifications.firebaseapp.com',
+  projectId: 'hostbbq-fcm-notifications',
+  storageBucket: 'hostbbq-fcm-notifications.appspot.com',
+  messagingSenderId: '297006222561',
+  appId: '1:297006222561:web:feb0463afb4b91c2cf3ba0'
+};
+
+@Injectable({
+  providedIn: 'root'
+})
+export class FirebaseService {
+  private _app: FirebaseApp;
+  private _fcm: Messaging;
+  private _analytics: Analytics;
+  private _regToken?: string;
+
+  constructor(private http: HttpClient) {
+    this._app = initializeApp(firebaseConfig);
+    this._fcm = getMessaging(this._app);
+    this._analytics = getAnalytics(this._app);
+  }
+
+  public async requestPermission(): Promise<void> {
+    const permission = await Notification.requestPermission();
+    if (permission === 'granted') {
+      return;
+    }
+    throw new Error('Notification Permission was not granted');
+  }
+
+  public async getRegistrationToken() {
+    if (!this._regToken) {
+      this._regToken = await getToken(this._fcm, {
+        vapidKey: 'BHUjnACHbTlNFjSQ8knXpGScoN3vUFvE2ZoK1hE7pGZGktygSGvhfHsI_rT1rkgbi3HKxak5I6qK06UJPpkEbD8'
+      });
+    }
+    return this._regToken;
+  }
+
+  public get topics() {
+    return ['monitoring-services'];
+  }
+
+  public async getInstanceInfo(): Promise<FirebaseInstanceInformation> {
+    const regToken = await this.getRegistrationToken();
+    return firstValueFrom(this.http.get<FirebaseInstanceInformation>(`${environment.apiBaseUrl}/topics/${regToken}`));
+  }
+
+  public async subscribeToTopic(topic: string) {
+    const regToken = await this.getRegistrationToken();
+    return firstValueFrom(
+      this.http
+        .put<{ ok: boolean }>(`${environment.apiBaseUrl}/topics/${topic}/${regToken}`, null)
+        .pipe(tap(text => console.log('[API RESPONSE]', text)))
+    );
+  }
+
+  public async unsubscribeFromTopic(topic: string) {
+    const regToken = await this.getRegistrationToken();
+    return firstValueFrom(
+      this.http
+        .delete<{ ok: boolean }>(`${environment.apiBaseUrl}/topics/${topic}/${regToken}`)
+        .pipe(tap(text => console.log('[API RESPONSE]', text)))
+    );
+  }
+}

+ 0 - 0
fcm/ng/src/assets/.gitkeep


+ 4 - 0
fcm/ng/src/environments/environment.prod.ts

@@ -0,0 +1,4 @@
+export const environment = {
+  production: true,
+  apiBaseUrl: ''
+};

+ 17 - 0
fcm/ng/src/environments/environment.ts

@@ -0,0 +1,17 @@
+// This file can be replaced during build by using the `fileReplacements` array.
+// `ng build` replaces `environment.ts` with `environment.prod.ts`.
+// The list of file replacements can be found in `angular.json`.
+
+export const environment = {
+  production: false,
+  apiBaseUrl: '/api'
+};
+
+/*
+ * For easier debugging in development mode, you can import the following file
+ * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
+ *
+ * This import should be commented out in production mode because it will have a negative impact
+ * on performance if an error is thrown.
+ */
+// import 'zone.js/plugins/zone-error';  // Included with Angular CLI.

BIN
fcm/ng/src/favicon.ico


+ 5 - 0
fcm/ng/src/firebase-messaging-sw.js

@@ -0,0 +1,5 @@
+self.addEventListener('push', event => {
+  const data = event.data.json();
+  console.log('[SW] PUSH', data);
+  event.waitUntil(self.registration.showNotification(data.notification.title, { body: data.notification.body, icon: data.notification.image }));
+});

+ 13 - 0
fcm/ng/src/index.html

@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8" />
+    <title>HostBBQ FCM Registration Page</title>
+    <base href="/" />
+    <meta name="viewport" content="width=device-width, initial-scale=1" />
+    <link rel="icon" type="image/x-icon" href="favicon.ico" />
+  </head>
+  <body>
+    <app-root></app-root>
+  </body>
+</html>

+ 12 - 0
fcm/ng/src/main.ts

@@ -0,0 +1,12 @@
+import { enableProdMode } from '@angular/core';
+import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
+
+import { AppModule } from './app/app.module';
+import { environment } from './environments/environment';
+
+if (environment.production) {
+  enableProdMode();
+}
+
+platformBrowserDynamic().bootstrapModule(AppModule)
+  .catch(err => console.error(err));

+ 53 - 0
fcm/ng/src/polyfills.ts

@@ -0,0 +1,53 @@
+/**
+ * This file includes polyfills needed by Angular and is loaded before the app.
+ * You can add your own extra polyfills to this file.
+ *
+ * This file is divided into 2 sections:
+ *   1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
+ *   2. Application imports. Files imported after ZoneJS that should be loaded before your main
+ *      file.
+ *
+ * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
+ * automatically update themselves. This includes recent versions of Safari, Chrome (including
+ * Opera), Edge on the desktop, and iOS and Chrome on mobile.
+ *
+ * Learn more in https://angular.io/guide/browser-support
+ */
+
+/***************************************************************************************************
+ * BROWSER POLYFILLS
+ */
+
+/**
+ * By default, zone.js will patch all possible macroTask and DomEvents
+ * user can disable parts of macroTask/DomEvents patch by setting following flags
+ * because those flags need to be set before `zone.js` being loaded, and webpack
+ * will put import in the top of bundle, so user need to create a separate file
+ * in this directory (for example: zone-flags.ts), and put the following flags
+ * into that file, and then add the following code before importing zone.js.
+ * import './zone-flags';
+ *
+ * The flags allowed in zone-flags.ts are listed here.
+ *
+ * The following flags will work for all browsers.
+ *
+ * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
+ * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
+ * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
+ *
+ *  in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
+ *  with the following flag, it will bypass `zone.js` patch for IE/Edge
+ *
+ *  (window as any).__Zone_enable_cross_context_check = true;
+ *
+ */
+
+/***************************************************************************************************
+ * Zone JS is required by default for Angular itself.
+ */
+import 'zone.js';  // Included with Angular CLI.
+
+
+/***************************************************************************************************
+ * APPLICATION IMPORTS
+ */

+ 21 - 0
fcm/ng/src/styles.scss

@@ -0,0 +1,21 @@
+@import '../../../bootstrap-theme/scss/bootstrap.scss';
+
+.pointer,
+.pointer input[type='checkbox' i],
+.pointer label {
+  cursor: pointer;
+}
+
+.form-check-input,
+.form-check-input:active,
+.form-check-input:focus {
+  // background-color: $danger;
+  border-color: $danger;
+}
+
+.form-check-input:checked,
+.form-check-input:checked:active,
+.form-check-input:checked:focus {
+  background-color: $success;
+  border-color: $success;
+}

+ 26 - 0
fcm/ng/src/test.ts

@@ -0,0 +1,26 @@
+// This file is required by karma.conf.js and loads recursively all the .spec and framework files
+
+import 'zone.js/testing';
+import { getTestBed } from '@angular/core/testing';
+import {
+  BrowserDynamicTestingModule,
+  platformBrowserDynamicTesting
+} from '@angular/platform-browser-dynamic/testing';
+
+declare const require: {
+  context(path: string, deep?: boolean, filter?: RegExp): {
+    <T>(id: string): T;
+    keys(): string[];
+  };
+};
+
+// First, initialize the Angular testing environment.
+getTestBed().initTestEnvironment(
+  BrowserDynamicTestingModule,
+  platformBrowserDynamicTesting(),
+);
+
+// Then we find all the tests.
+const context = require.context('./', true, /\.spec\.ts$/);
+// And load the modules.
+context.keys().forEach(context);

+ 15 - 0
fcm/ng/tsconfig.app.json

@@ -0,0 +1,15 @@
+/* To learn more about this file see: https://angular.io/config/tsconfig. */
+{
+  "extends": "./tsconfig.json",
+  "compilerOptions": {
+    "outDir": "./out-tsc/app",
+    "types": []
+  },
+  "files": [
+    "src/main.ts",
+    "src/polyfills.ts"
+  ],
+  "include": [
+    "src/**/*.d.ts"
+  ]
+}

+ 32 - 0
fcm/ng/tsconfig.json

@@ -0,0 +1,32 @@
+/* To learn more about this file see: https://angular.io/config/tsconfig. */
+{
+  "compileOnSave": false,
+  "compilerOptions": {
+    "baseUrl": "./",
+    "outDir": "./dist/out-tsc",
+    "forceConsistentCasingInFileNames": true,
+    "strict": true,
+    "noImplicitOverride": true,
+    "noPropertyAccessFromIndexSignature": true,
+    "noImplicitReturns": true,
+    "noFallthroughCasesInSwitch": true,
+    "sourceMap": true,
+    "declaration": false,
+    "downlevelIteration": true,
+    "experimentalDecorators": true,
+    "moduleResolution": "node",
+    "importHelpers": true,
+    "target": "es2020",
+    "module": "es2020",
+    "lib": [
+      "es2020",
+      "dom"
+    ]
+  },
+  "angularCompilerOptions": {
+    "enableI18nLegacyMessageIdFormat": false,
+    "strictInjectionParameters": true,
+    "strictInputAccessModifiers": true,
+    "strictTemplates": true
+  }
+}

+ 18 - 0
fcm/ng/tsconfig.spec.json

@@ -0,0 +1,18 @@
+/* To learn more about this file see: https://angular.io/config/tsconfig. */
+{
+  "extends": "./tsconfig.json",
+  "compilerOptions": {
+    "outDir": "./out-tsc/spec",
+    "types": [
+      "jasmine"
+    ]
+  },
+  "files": [
+    "src/test.ts",
+    "src/polyfills.ts"
+  ],
+  "include": [
+    "src/**/*.spec.ts",
+    "src/**/*.d.ts"
+  ]
+}

+ 1 - 1
ng/angular.json

@@ -25,7 +25,7 @@
             "inlineStyleLanguage": "scss",
             "assets": ["src/favicon.ico", "src/assets"],
             "styles": ["src/styles.scss"],
-            "scripts": ["bootstrap-theme/dist/js/bootstrap.js"]
+            "scripts": ["../bootstrap-theme/dist/js/bootstrap.js"]
           },
           "configurations": {
             "production": {

+ 1 - 1
ng/src/styles.scss

@@ -1,4 +1,4 @@
-@import '../bootstrap-theme/scss/bootstrap.scss';
+@import '../../bootstrap-theme/scss/bootstrap.scss';
 
 .pointer {
   cursor: pointer;

+ 3 - 1
server/.env.default

@@ -1,3 +1,5 @@
 LOG_LEVEL=INFO
 WEB_PORT=8880
-DATA_DIR=data
+DATA_DIR=data
+GOOGLE_APPLICATION_CREDENTIALS="google-cloud/firebase-adminsdk.json"
+NOTIFICATION_ICON_URL="https://fcm.hostbbq.net/logo.png"

+ 34 - 1
server/docs/Monitoring.postman_collection.json

@@ -127,7 +127,7 @@
 						"header": [],
 						"body": {
 							"mode": "raw",
-							"raw": "{\r\n    \"title\": \"kaytobee.de\",\r\n    \"type\": \"http\",\r\n    \"url\": \"https://www.kaytobee.de\",\r\n    \"interval\": 50,\r\n    \"active\": true,\r\n    \"timeout\": 10000,\r\n    \"checks\": [\r\n        \"kaytobee\",\r\n        \"kaytobee\\\\.(com|de|fr)\",\r\n        \"reg|exp\"\r\n    ]\r\n}",
+							"raw": "{\r\n    \"id\": 3,\r\n    \"title\": \"kaytobee.de\",\r\n    \"type\": \"http\",\r\n    \"serverId\": 2,\r\n    \"url\": \"https://kaytobee.de\",\r\n    \"active\": true,\r\n    \"interval\": 270,\r\n    \"timeout\": 10000,\r\n    \"notify\": true,\r\n    \"notifyThreshold\": 3,\r\n    \"checks\": [\r\n        \"kaytobee\",\r\n        \"kaytobee\\\\.de\",\r\n        \"<title>[^<]*(kaytobee)[^<]*</title>\"\r\n    ]\r\n}",
 							"options": {
 								"raw": {
 									"language": "json"
@@ -210,6 +210,39 @@
 						}
 					},
 					"response": []
+				},
+				{
+					"name": "/fcm/topics/{:topic}",
+					"request": {
+						"method": "POST",
+						"header": [],
+						"body": {
+							"mode": "raw",
+							"raw": "{\r\n    \"title\": \"HostBBQ Monitoring Notification\",\r\n    \"body\": \"First Test from Monitoring Backend via Firebase Admin SDK\"\r\n}",
+							"options": {
+								"raw": {
+									"language": "json"
+								}
+							}
+						},
+						"url": {
+							"raw": "http://10.8.0.1:8880/fcm/topics/monitoring-services",
+							"protocol": "http",
+							"host": [
+								"10",
+								"8",
+								"0",
+								"1"
+							],
+							"port": "8880",
+							"path": [
+								"fcm",
+								"topics",
+								"monitoring-services"
+							]
+						}
+					},
+					"response": []
 				}
 			]
 		}

+ 15 - 1
server/install/install.sh

@@ -24,6 +24,20 @@ if [ -z "$EXC_NODE" ]; then
   exit 1
 fi
 
+GCC_CONFIG_DIR="${INSTALL_DIR}/google-cloud"
+FCM_ACCOUNT_JSON="${GCC_CONFIG_DIR}/firebase-adminsdk.json"
+
+if [ ! -d "$GCC_CONFIG_DIR" ]; then
+  echo "[ERROR] Missing required google cloud key files. Please prepare directory 'google-cloud' in install directory." >&2
+  exit 1
+fi
+
+if [ ! -f "$FCM_ACCOUNT_JSON" ]; then
+  echo "[ERROR] Missing required Firebase Admin SDK key file. Please provide this file as 'google-cloud/firebase-adminsdk.json' in order to install." >&2
+  exit 1
+fi
+
+
 # exit on error exit codes
 set -e
 
@@ -45,7 +59,7 @@ $EXC_NPM install
 
 cd "$TMPFOLDER/ng"
 echo "[INSTALL] Installing npm build dependencies for Angular project"
-$EXC_NPM install
+$EXC_NPM install --legacy-peer-deps
 
 echo "[INSTALL] Building Angular project"
 $EXC_NPM run build

+ 1 - 0
server/package.json

@@ -13,6 +13,7 @@
     "axios": "^0.27.2",
     "dotenv": "^16.0.2",
     "express": "^4.18.1",
+    "firebase-admin": "^11.4.1",
     "moment": "^2.29.4",
     "sqlite3": "^5.1.1"
   },

+ 107 - 20
server/src/ctrl/database.class.ts

@@ -324,6 +324,9 @@ export class Database extends SQLiteController {
           updValues.push([conf.active ?? defaults.serviceChecks.active ? 1 : 0, conf.id, 'active']);
           status = conf.active ?? defaults.serviceChecks.active ? ServiceChangedStatus.Activated : ServiceChangedStatus.Deactivated;
         }
+        if (oldConf.notify !== conf.notify) updValues.push([conf.notify ?? defaults.serviceChecks.notify ? 1 : 0, conf.id, 'notify']);
+        if (oldConf.notifyThreshold !== conf.notifyThreshold)
+          updValues.push([conf.notifyThreshold ?? defaults.serviceChecks.notifyThreshold, conf.id, 'notifyThreshold']);
         if (updValues.length) {
           for (const data of updValues) {
             await this.run(`UPDATE HealthCheckParams SET Value = ? WHERE ConfigID = ? AND Key = ?;`, data);
@@ -342,8 +345,8 @@ export class Database extends SQLiteController {
         });
 
         if (delIDs.length) {
-          const delSql = 'DELETE FROM HealthCheckParams WHERE ID IN (?);';
-          await this.run(delSql, [delIDs]);
+          const delSql = `DELETE FROM HealthCheckParams WHERE ID IN (${delIDs.map(() => '?').join(',')});`;
+          await this.run(delSql, delIDs);
         }
 
         if (updValues.length) {
@@ -371,12 +374,16 @@ export class Database extends SQLiteController {
           (?, ?, ?, ?),
           (?, ?, ?, ?),
           (?, ?, ?, ?),
+          (?, ?, ?, ?),
+          (?, ?, ?, ?),
           (?, ?, ?, ?)${conf.checks.length ? `,${insCheckValues.map(() => '(?, ?, ?, ?)').join(',')}` : ''}`,
           [
             ...[res.lastID, 'text', 'url', conf.url],
             ...[res.lastID, 'boolean', 'active', conf.active ?? defaults.serviceChecks.active ? 1 : 0],
             ...[res.lastID, 'number', 'interval', conf.interval],
             ...[res.lastID, 'number', 'timeout', conf.timeout ?? defaults.serviceChecks.httpTimeout],
+            ...[res.lastID, 'boolean', 'notify', conf.notify ?? defaults.serviceChecks.notify],
+            ...[res.lastID, 'number', 'notifyThreshold', conf.notifyThreshold ?? defaults.serviceChecks.notifyThreshold],
             ...conf.checks.reduce((ret, check) => [...ret, res.lastID, 'regexp', 'check', check], [] as any[])
           ]
         );
@@ -418,27 +425,59 @@ export class Database extends SQLiteController {
   async queryServiceCheckData(serverID: number, confID: number, from: Date, to: Date) {
     const result = await this.stmt(
       `
-      SELECT 
-        HealthCheckDataEntry.*
-      FROM HealthCheckDataEntry
-      JOIN HealthCheckConfig ON HealthCheckConfig.ID = HealthCheckDataEntry.ConfigID
+      SELECT DataEntryChanges.*
+      FROM HealthCheckConfig
+      JOIN (
+        SELECT * FROM (
+          SELECT 
+            *
+          FROM HealthCheckDataEntry
+          WHERE ConfigID = ?
+          AND Timestamp BETWEEN ? AND ?
+          ORDER BY ID
+          LIMIT 0, 1
+        ) AS FIRST_STATE
+
+        UNION --+--+--
+
+        SELECT 
+          ID,
+          ConfigID,
+          Timestamp,
+          Status,
+          Message
+        FROM
+        (
+          SELECT 
+            HealthCheckDataEntry.*, 
+            LAG(Status) OVER (ORDER BY ConfigID, Timestamp) AS previous_state, 
+            LAG(Message) OVER (ORDER BY ConfigID, Timestamp) AS previous_msg
+          FROM HealthCheckDataEntry
+          WHERE ConfigID = ?
+        )
+        WHERE Status <> previous_state
+        AND Message <> previous_msg
+        
+        UNION --+--+--
+        
+        SELECT * FROM (
+          SELECT 
+            *
+          FROM HealthCheckDataEntry
+          WHERE ConfigID = ?
+          AND Timestamp BETWEEN ? AND ?
+          ORDER BY ID DESC
+          LIMIT 0, 1
+        ) AS LAST_STATE
+        ORDER BY ConfigID, Timestamp
+      ) AS DataEntryChanges ON DataEntryChanges.ConfigID = HealthCheckConfig.ID
       WHERE HealthCheckConfig.ServerID = ?
-        AND HealthCheckDataEntry.ConfigID = ?
-        AND HealthCheckDataEntry.Timestamp BETWEEN ? AND ?
-      ORDER BY Timestamp, ID;
-    `,
-      [serverID, confID, from.getTime(), to.getTime()]
+        AND DataEntryChanges.Timestamp BETWEEN ? AND ?
+      ORDER BY Timestamp, ID;`,
+      [confID, from.getTime(), to.getTime(), confID, confID, from.getTime(), to.getTime(), serverID, from.getTime(), to.getTime()]
     );
 
-    const mapByTimestamp = result.rows.reduce((res: Map<number, ServiceCheckDataEntry[]>, row) => {
-      const time: number = row['Timestamp'];
-      if (!res.has(time)) res.set(time, []);
-      res.get(time)?.push({
-        status: row['Status'] as number,
-        message: row['Message']
-      });
-      return res;
-    }, new Map()) as Map<number, ServiceCheckDataEntry[]>;
+    const mapByTimestamp = this.mapServiceCheckDataByTimestamp(result.rows);
 
     const arr: ServiceCheckData[] = [];
     for (const entry of mapByTimestamp.entries()) {
@@ -450,6 +489,52 @@ export class Database extends SQLiteController {
     return arr;
   }
 
+  public async getLastErrors(confID: number, threshold: number) {
+    const result = await this.stmt(
+      `SELECT * FROM HealthCheckDataEntry
+        WHERE ConfigID = ?
+        AND Timestamp IN (
+          SELECT Timestamp 
+          FROM HealthCheckDataEntry
+          WHERE ConfigID = ?
+          GROUP BY Timestamp
+          ORDER BY Timestamp DESC
+          LIMIT 0, ?
+        )
+        ORDER BY Timestamp DESC, ID DESC`,
+      [confID, confID, threshold]
+    );
+
+    const mapByTimestamp = this.mapServiceCheckDataByTimestamp(result.rows);
+    const errors: ServiceCheckData[] = [];
+    for (const entry of mapByTimestamp.entries()) {
+      const time = entry[0];
+      const data = entry[1];
+
+      const errorData = data.filter(d => d.status !== HttpCheckStatus.OK);
+      if (!errorData.length) break;
+
+      errors.push({
+        time: new Date(time),
+        data: errorData
+      });
+    }
+
+    return errors;
+  }
+
+  private mapServiceCheckDataByTimestamp(rows: any[]) {
+    return rows.reduce((res: Map<number, ServiceCheckDataEntry[]>, row) => {
+      const time: number = row['Timestamp'];
+      if (!res.has(time)) res.set(time, []);
+      res.get(time)?.push({
+        status: row['Status'] as number,
+        message: row['Message']
+      });
+      return res;
+    }, new Map()) as Map<number, ServiceCheckDataEntry[]>;
+  }
+
   private configFromResultRows(rows: any[]) {
     return rows.reduce((res: ServiceConfig[], line, i) => {
       const configID = line['ID'];
@@ -502,6 +587,8 @@ export class Database extends SQLiteController {
       active: (hcConf.params?.find(p => p.key === 'active')?.value as boolean) ?? defaults.serviceChecks.active,
       interval: hcConf.params?.find(p => p.key === 'interval')?.value as number,
       timeout: (hcConf.params?.find(p => p.key === 'timeout')?.value as number) ?? defaults.serviceChecks.httpTimeout,
+      notify: (hcConf.params?.find(p => p.key === 'notify')?.value as boolean) ?? defaults.serviceChecks.notify,
+      notifyThreshold: (hcConf.params?.find(p => p.key === 'notifyThreshold')?.value as number) ?? defaults.serviceChecks.notifyThreshold,
       checks: hcConf.params?.reduce((res, p) => (p.key === 'check' && Array.isArray(p.value) ? [...res, ...p.value] : res), [] as string[])
     };
     return {

+ 48 - 0
server/src/ctrl/fcm-controller.class.ts

@@ -0,0 +1,48 @@
+import firebaseAdmin from 'firebase-admin';
+
+export class FCMController {
+  private static INSTANCE?: FCMController;
+
+  private app: firebaseAdmin.app.App;
+  private messaging;
+
+  private constructor() {
+    // Uses ENV GOOGLE_APPLICATION_CREDENTIALS to load credentials file
+    this.app = firebaseAdmin.initializeApp();
+    this.messaging = this.app.messaging();
+  }
+
+  public static get instance(): FCMController {
+    if (!FCMController.INSTANCE) {
+      FCMController.INSTANCE = new FCMController();
+    }
+    return FCMController.INSTANCE;
+  }
+
+  public async sendNotificationToTopic(topic: string, notification: { title: string; body: string }) {
+    console.log('ICON URL:', process.env.NOTIFICATION_ICON_URL);
+
+    const response = await this.messaging.send({
+      notification: {
+        imageUrl: process.env.NOTIFICATION_ICON_URL ?? '',
+        ...notification
+      },
+      android: {
+        notification: {
+          icon: process.env.NOTIFICATION_ICON_URL ?? '',
+          imageUrl: process.env.NOTIFICATION_ICON_URL ?? ''
+        }
+      },
+      webpush: {
+        headers: {
+          image: process.env.NOTIFICATION_ICON_URL ?? ''
+        },
+        notification: {
+          icon: process.env.NOTIFICATION_ICON_URL ?? ''
+        }
+      },
+      topic
+    });
+    return response;
+  }
+}

+ 40 - 18
server/src/ctrl/http-check-controller.class.ts

@@ -1,11 +1,15 @@
 import axios, { AxiosError, AxiosRequestConfig } from 'axios';
+import moment from 'moment';
 
 import defaults from '../../../common/defaults.module';
 import { HttpCheckStatus } from '../../../common/lib/http-check-data.module';
 import { Logger } from '../../../common/util/logger.class';
 
-import { Database, ServiceChangedStatus } from './database.class';
 import { Timer } from '../timer.class';
+import { Database, ServiceChangedStatus } from './database.class';
+import { FCMController } from './fcm-controller.class';
+
+const FCM_TOPIC_SERVICES = 'monitoring-services';
 
 type Subscriber = { id: number; interval: number; conf: HttpCheckConfig };
 
@@ -20,17 +24,15 @@ export class HttpCheckController {
         await this.db.open();
         const configs = await this.db.getHttpCheckConfigs();
 
-        configs.forEach(async conf => {
+        for (const conf of configs) {
           if (!conf) return;
           if (!conf.active) return;
 
-          const sub = await this.scheduleCheck(conf);
+          await this.scheduleCheck(conf);
 
-          process.nextTick(async () => {
-            Logger.info('[INFO] Initial HTTP Service Check for', conf.title, '...');
-            await this.timerTick(conf);
-          });
-        });
+          Logger.info('[INFO] Initial HTTP Service Check for', conf.title, '...');
+          await this.timerTick(conf);
+        }
       } catch (err) {
         Logger.error('[FATAL] Initializing ServerConnector failed:', err);
         Logger.error('[EXITING]');
@@ -91,34 +93,36 @@ export class HttpCheckController {
       timeout: conf.timeout,
       responseType: 'text'
     };
+    let success = true;
     try {
-      const current = await this.db.getHttpCheckConfigByID(conf.serverId ?? 0, conf.id);
+      const id = conf.id;
+      conf = (await this.db.getHttpCheckConfigByID(conf.serverId ?? 0, id)) as HttpCheckConfig;
 
-      if (!current) {
-        Logger.warn(`[WARN] HealthCheckConfig(${conf.id}) not found in Database but still scheduled in Timer!`);
+      if (!conf) {
+        Logger.warn(`[WARN] HealthCheckConfig(${id}) not found in Database but still scheduled in Timer!`);
         return;
       }
 
-      options.timeout = current.timeout;
-      let response = await axios.get(current.url, options);
+      options.timeout = conf.timeout;
+      let response = await axios.get(conf.url, options);
       const responseText = new String(response.data).toString();
 
-      let success = true;
-      for (const check of current.checks) {
+      for (const check of conf.checks) {
         const reg = new RegExp(check, 'i');
         if (!reg.test(responseText)) {
           Logger.debug(`[DEBUG] Regular expression /${check}/i not found in response`);
-          await this.db.insertHealthCheckData(current.id, now, HttpCheckStatus.CheckFailed, `Regular expression /${check}/i not found in response`);
+          await this.db.insertHealthCheckData(conf.id, now, HttpCheckStatus.CheckFailed, `Regular expression /${check}/i not found in response`);
           success = false;
         }
       }
 
       if (success) {
-        Logger.debug(`[DEBUG] HTTP Service Check "${current.title}": OK.`);
-        await this.db.insertHealthCheckData(current.id, now, HttpCheckStatus.OK, 'OK');
+        Logger.debug(`[DEBUG] HTTP Service Check "${conf.title}": OK.`);
+        await this.db.insertHealthCheckData(conf.id, now, HttpCheckStatus.OK, 'OK');
       }
     } catch (err) {
       let log = false;
+      success = false;
       if (err instanceof AxiosError) {
         // err.code = 'ECONNREFUSED' | 'ECONNABORTED' | 'ERR_BAD_REQUEST' | 'ERR_BAD_RESPONSE' | ...?
         try {
@@ -143,6 +147,24 @@ export class HttpCheckController {
       }
       if (log) Logger.error('[ERROR] HTTP Service Check failed:', err);
     }
+    if (!success && conf.notify) {
+      try {
+        const lastErrors = await this.db.getLastErrors(conf.id, conf.notifyThreshold + 1);
+        if (lastErrors.length > conf.notifyThreshold) {
+          Logger.debug(`[DEBUG] Sending FCM Notification for`, conf.title);
+          const lastCheck = lastErrors[0];
+          const lastError = lastCheck.data[0];
+          await FCMController.instance.sendNotificationToTopic(FCM_TOPIC_SERVICES, {
+            title: `[CRIT] ${conf.title} since ${moment(lastCheck.time).format('HH:mm')}`,
+            body:
+              `HTTP Check '${conf.title}' has failed over ${conf.notifyThreshold} times in a row\n` +
+              `Last error status was: (${lastError.status}) ${lastError.message}`
+          });
+        }
+      } catch (err) {
+        Logger.error('[ERROR] Notification failure:', err);
+      }
+    }
   }
 
   async close() {

+ 7 - 0
server/src/migrations/202212301910_website_healthcheck_notification_defaults.sql

@@ -0,0 +1,7 @@
+INSERT INTO HealthCheckParams(ConfigID, Type, Key, Value)
+  SELECT ID, 'boolean', 'notify', '0'
+  FROM HealthCheckConfig;
+
+INSERT INTO HealthCheckParams(ConfigID, Type, Key, Value)
+  SELECT ID, 'number', 'notifyThreshold', '3'
+  FROM HealthCheckConfig;

+ 27 - 0
server/src/webhdl/fcm-api-handler.class.ts

@@ -0,0 +1,27 @@
+import { json, RouterOptions } from 'express';
+
+import { ControllerPool } from '../ctrl/controller-pool.interface';
+import { FCMController } from '../ctrl/fcm-controller.class';
+import { WebHandler } from './web-handler.base';
+
+export class FCMAPIHandler extends WebHandler {
+  constructor(protected ctrlPool: ControllerPool, options?: RouterOptions) {
+    super(ctrlPool, options);
+
+    this.router.use(json());
+    this.router.use(this.avoidCache);
+
+    this.router.post('/topics/:topic', async (req, res, next) => {
+      try {
+        const topic = req.params.topic;
+        const notification = req.body;
+
+        const messageId = await FCMController.instance.sendNotificationToTopic(topic, notification);
+
+        res.status(201).send({ sent: true, id: messageId });
+      } catch (err) {
+        next(err);
+      }
+    });
+  }
+}

+ 3 - 0
server/src/webserver.class.ts

@@ -6,6 +6,7 @@ import { Logger } from '../../common/util/logger.class';
 
 import { ControllerPool } from './ctrl/controller-pool.interface';
 import { ValidationException } from './lib/validation-exception.class';
+import { FCMAPIHandler } from './webhdl/fcm-api-handler.class';
 import { ServerAPIHandler } from './webhdl/server-api-handler.class';
 import { ServicesAPIHandler } from './webhdl/services-api-handler.class';
 
@@ -15,6 +16,8 @@ export class Webserver {
   constructor(private port: number, ctrlPool: ControllerPool) {
     this.app = express();
 
+    const fcmApi = new FCMAPIHandler(ctrlPool);
+    this.app.use('/fcm', fcmApi.router);
     const serverApi = new ServerAPIHandler(ctrlPool);
     this.app.use('/server', serverApi.router);
     const servicesApi = new ServicesAPIHandler(ctrlPool);