]> git.proxmox.com Git - ceph.git/blob - ceph/src/pybind/mgr/dashboard/frontend/src/app/shared/services/motd-notification.service.ts
import ceph 15.2.14
[ceph.git] / ceph / src / pybind / mgr / dashboard / frontend / src / app / shared / services / motd-notification.service.ts
1 import { Injectable, OnDestroy } from '@angular/core';
2
3 import * as _ from 'lodash';
4 import { BehaviorSubject, EMPTY, Observable, of, Subscription } from 'rxjs';
5 import { catchError, delay, mergeMap, repeat, tap } from 'rxjs/operators';
6
7 import { Motd, MotdService } from '../api/motd.service';
8
9 @Injectable({
10 providedIn: 'root'
11 })
12 export class MotdNotificationService implements OnDestroy {
13 public motd$: Observable<Motd | null>;
14 public motdSource = new BehaviorSubject<Motd | null>(null);
15
16 private subscription: Subscription;
17 private localStorageKey = 'dashboard_motd_hidden';
18
19 constructor(private motdService: MotdService) {
20 this.motd$ = this.motdSource.asObservable();
21 // Check every 60 seconds for the latest MOTD configuration.
22 this.subscription = of(true)
23 .pipe(
24 mergeMap(() => this.motdService.get()),
25 catchError((error) => {
26 // Do not show an error notification.
27 if (_.isFunction(error.preventDefault)) {
28 error.preventDefault();
29 }
30 return EMPTY;
31 }),
32 tap((motd: Motd | null) => this.processResponse(motd)),
33 delay(60000),
34 repeat()
35 )
36 .subscribe();
37 }
38
39 ngOnDestroy(): void {
40 this.subscription.unsubscribe();
41 }
42
43 hide() {
44 // Store the severity and MD5 of the current MOTD in local or
45 // session storage to be able to show it again if the severity
46 // or message of the latest MOTD has changed.
47 const motd: Motd = this.motdSource.getValue();
48 if (motd) {
49 const value = `${motd.severity}:${motd.md5}`;
50 switch (motd.severity) {
51 case 'info':
52 localStorage.setItem(this.localStorageKey, value);
53 sessionStorage.removeItem(this.localStorageKey);
54 break;
55 case 'warning':
56 sessionStorage.setItem(this.localStorageKey, value);
57 localStorage.removeItem(this.localStorageKey);
58 break;
59 }
60 }
61 this.motdSource.next(null);
62 }
63
64 processResponse(motd: Motd | null) {
65 const value: string | null =
66 sessionStorage.getItem(this.localStorageKey) || localStorage.getItem(this.localStorageKey);
67 let visible: boolean = _.isNull(value);
68 // Force a hidden MOTD to be shown again if the severity or message
69 // has been changed.
70 if (!visible && motd) {
71 const [severity, md5] = value.split(':');
72 if (severity !== motd.severity || md5 !== motd.md5) {
73 visible = true;
74 sessionStorage.removeItem(this.localStorageKey);
75 localStorage.removeItem(this.localStorageKey);
76 }
77 }
78 if (visible) {
79 this.motdSource.next(motd);
80 }
81 }
82 }