1 import { Injectable, OnDestroy } from '@angular/core';
3 import * as _ from 'lodash';
4 import { BehaviorSubject, EMPTY, Observable, of, Subscription } from 'rxjs';
5 import { catchError, delay, mergeMap, repeat, tap } from 'rxjs/operators';
7 import { Motd, MotdService } from '~/app/shared/api/motd.service';
8 import { whenPageVisible } from '../rxjs/operators/page-visibilty.operator';
13 export class MotdNotificationService implements OnDestroy {
14 public motd$: Observable<Motd | null>;
15 public motdSource = new BehaviorSubject<Motd | null>(null);
17 private subscription: Subscription;
18 private localStorageKey = 'dashboard_motd_hidden';
20 constructor(private motdService: MotdService) {
21 this.motd$ = this.motdSource.asObservable();
22 // Check every 60 seconds for the latest MOTD configuration.
23 this.subscription = of(true)
25 mergeMap(() => this.motdService.get()),
26 catchError((error) => {
27 // Do not show an error notification.
28 if (_.isFunction(error.preventDefault)) {
29 error.preventDefault();
33 tap((motd: Motd | null) => this.processResponse(motd)),
42 this.subscription.unsubscribe();
46 // Store the severity and MD5 of the current MOTD in local or
47 // session storage to be able to show it again if the severity
48 // or message of the latest MOTD has changed.
49 const motd: Motd = this.motdSource.getValue();
51 const value = `${motd.severity}:${motd.md5}`;
52 switch (motd.severity) {
54 localStorage.setItem(this.localStorageKey, value);
55 sessionStorage.removeItem(this.localStorageKey);
58 sessionStorage.setItem(this.localStorageKey, value);
59 localStorage.removeItem(this.localStorageKey);
63 this.motdSource.next(null);
66 processResponse(motd: Motd | null) {
67 const value: string | null =
68 sessionStorage.getItem(this.localStorageKey) || localStorage.getItem(this.localStorageKey);
69 let visible: boolean = _.isNull(value);
70 // Force a hidden MOTD to be shown again if the severity or message
72 if (!visible && motd) {
73 const [severity, md5] = value.split(':');
74 if (severity !== motd.severity || md5 !== motd.md5) {
76 sessionStorage.removeItem(this.localStorageKey);
77 localStorage.removeItem(this.localStorageKey);
81 this.motdSource.next(motd);