Переглянути джерело

Implementation of FCM Registration Service (ng+express.js)

Christian Kahlau 3 роки тому
батько
коміт
c18d1a558b

+ 6 - 1
.gitignore

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

+ 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 -
+```

+ 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"
+  }
+}

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

@@ -0,0 +1,86 @@
+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();
+
+(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.use('/', express.static('public'));
+
+    server.use('**', express.static(path.join('public', '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 {
+        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.

+ 97 - 0
fcm/ng/angular.json

@@ -0,0 +1,97 @@
+{
+  "$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": []
+          }
+        }
+      }
+    }
+  }
+}

+ 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"
+  ]
+}