]> git.proxmox.com Git - ceph.git/blob - ceph/src/pybind/mgr/dashboard/frontend/src/app/shared/services/motd-notification.service.ts
bump version to 18.2.2-pve1
[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 '~/app/shared/api/motd.service';
8 import { whenPageVisible } from '../rxjs/operators/page-visibilty.operator';
9
10 @Injectable({
11 providedIn: 'root'
12 })
13 export class MotdNotificationService implements OnDestroy {
14 public motd$: Observable<Motd | null>;
15 public motdSource = new BehaviorSubject<Motd | null>(null);
16
17 private subscription: Subscription;
18 private localStorageKey = 'dashboard_motd_hidden';
19
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)
24 .pipe(
25 mergeMap(() => this.motdService.get()),
26 catchError((error) => {
27 // Do not show an error notification.
28 if (_.isFunction(error.preventDefault)) {
29 error.preventDefault();
30 }
31 return EMPTY;
32 }),
33 tap((motd: Motd | null) => this.processResponse(motd)),
34 delay(60000),
35 repeat(),
36 whenPageVisible()
37 )
38 .subscribe();
39 }
40
41 ngOnDestroy(): void {
42 this.subscription.unsubscribe();
43 }
44
45 hide() {
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();
50 if (motd) {
51 const value = `${motd.severity}:${motd.md5}`;
52 switch (motd.severity) {
53 case 'info':
54 localStorage.setItem(this.localStorageKey, value);
55 sessionStorage.removeItem(this.localStorageKey);
56 break;
57 case 'warning':
58 sessionStorage.setItem(this.localStorageKey, value);
59 localStorage.removeItem(this.localStorageKey);
60 break;
61 }
62 }
63 this.motdSource.next(null);
64 }
65
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
71 // has been changed.
72 if (!visible && motd) {
73 const [severity, md5] = value.split(':');
74 if (severity !== motd.severity || md5 !== motd.md5) {
75 visible = true;
76 sessionStorage.removeItem(this.localStorageKey);
77 localStorage.removeItem(this.localStorageKey);
78 }
79 }
80 if (visible) {
81 this.motdSource.next(motd);
82 }
83 }
84 }