All files / src/app/shared/services notification.service.ts

97.14% Statements 68/70
82.35% Branches 14/17
93.33% Functions 14/15
96.88% Lines 62/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 18648x   48x 48x 48x   48x 48x   48x 48x 48x         48x 505x     505x 505x     505x     505x     505x 505x 505x   505x 505x     11x   36x   308x       505x           48x 18x 18x           48x 23x 23x   5x   23x 23x     48x 25x 25x 25x 23x       48x 23x 35x   23x                                         48x             36x     7x   5x   17x               29x 29x 29x       48x         29x               48x 29x             48x     10x         2x           12x             48x 31x             48x     48x  
import { Injectable } from '@angular/core';
 
import * as _ from 'lodash';
import { ToastOptions, ToastsManager } from 'ng2-toastr';
import { BehaviorSubject } from 'rxjs';
 
import { NotificationType } from '../enum/notification-type.enum';
import { CdNotification, CdNotificationConfig } from '../models/cd-notification';
import { FinishedTask } from '../models/finished-task';
import { CdDatePipe } from '../pipes/cd-date.pipe';
import { ServicesModule } from './services.module';
import { TaskMessageService } from './task-message.service';
 
@Injectable({
  providedIn: ServicesModule
})
export class NotificationService {
  private hideToasties = false;
 
  // Observable sources
  private dataSource = new BehaviorSubject<CdNotification[]>([]);
  private queuedNotifications: CdNotificationConfig[] = [];
 
  // Observable streams
  data$ = this.dataSource.asObservable();
 
  private queueTimeoutId: number;
  KEY = 'cdNotifications';
 
  constructor(
    public toastr: ToastsManager,
    private taskMessageService: TaskMessageService,
    private cdDatePipe: CdDatePipe
  ) {
    const stringNotifications = localStorage.getItem(this.KEY);
    let notifications: CdNotification[] = [];
 
    if (_.isString(stringNotifications)) {
      notifications = JSON.parse(stringNotifications, (_key, value) => {
        if (_.isPlainObject(value)) {
          return _.assign(new CdNotification(), value);
        }
        return value;
      });
    }
 
    this.dataSource.next(notifications);
  }
 
  /**
   * Removes all current saved notifications
   */
  removeAll() {
    localStorage.removeItem(this.KEY);
    this.dataSource.next([]);
  }
 
  /**
   * Method used for saving a shown notification (check show() method).
   */
  save(notification: CdNotification) {
    const recent = this.dataSource.getValue();
    recent.push(notification);
    while (recent.length > 10) {
      recent.shift();
    }
    this.dataSource.next(recent);
    localStorage.setItem(this.KEY, JSON.stringify(recent));
  }
 
  queueNotifications(notifications: CdNotificationConfig[]) {
    this.queuedNotifications = this.queuedNotifications.concat(notifications);
    this.cancel(this.queueTimeoutId);
    this.queueTimeoutId = window.setTimeout(() => {
      this.sendQueuedNotifications();
    }, 500);
  }
 
  private sendQueuedNotifications() {
    _.uniqWith(this.queuedNotifications, _.isEqual).forEach((notification) => {
      this.show(notification);
    });
    this.queuedNotifications = [];
  }
 
  /**
   * Method for showing a notification.
   * @param {NotificationType} type toastr type
   * @param {string} title
   * @param {string} [message] The message to be displayed. Note, use this field
   *   for error notifications only.
   * @param {*} [options] toastr compatible options, used when creating a toastr
   * @param {string} [application] Only needed if notification comes from an external application
   * @returns The timeout ID that is set to be able to cancel the notification.
   */
  show(
    type: NotificationType,
    title: string,
    message?: string,
    options?: any | ToastOptions,
    application?: string
  ): number;
  show(config: CdNotificationConfig | (() => CdNotificationConfig)): number;
  show(
    arg: NotificationType | CdNotificationConfig | (() => CdNotificationConfig),
    title?: string,
    message?: string,
    options?: any | ToastOptions,
    application?: string
  ): number {
    return window.setTimeout(() => {
      let config: CdNotificationConfig;
      if (_.isFunction(arg)) {
        config = arg() as CdNotificationConfig;
      } else if (_.isObject(arg)) {
        config = arg as CdNotificationConfig;
      } else {
        config = new CdNotificationConfig(
          arg as NotificationType,
          title,
          message,
          options,
          application
        );
      }
      const notification = new CdNotification(config);
      this.save(notification);
      this.showToasty(notification);
    }, 10);
  }
 
  private showToasty(notification: CdNotification) {
    // Exit immediately if no toasty should be displayed.
    if (this.hideToasties) {
      return;
    }
    this.toastr[['error', 'info', 'success'][notification.type]](
      (notification.message ? notification.message + '<br>' : '') +
        this.renderTimeAndApplicationHtml(notification),
      notification.title,
      notification.options
    );
  }
 
  renderTimeAndApplicationHtml(notification: CdNotification): string {
    return `<small class="date">${this.cdDatePipe.transform(
      notification.timestamp
    )}</small><i class="pull-right custom-icon ${notification.applicationClass}" title="${
      notification.application
    }"></i>`;
  }
 
  notifyTask(finishedTask: FinishedTask, success: boolean = true): number {
    let notification: CdNotificationConfig;
    if (finishedTask.success && success) {
      notification = new CdNotificationConfig(
        NotificationType.success,
        this.taskMessageService.getSuccessTitle(finishedTask)
      );
    } else {
      notification = new CdNotificationConfig(
        NotificationType.error,
        this.taskMessageService.getErrorTitle(finishedTask),
        this.taskMessageService.getErrorMessage(finishedTask)
      );
    }
    return this.show(notification);
  }
 
  /**
   * Prevent the notification from being shown.
   * @param {number} timeoutId A number representing the ID of the timeout to be canceled.
   */
  cancel(timeoutId) {
    window.clearTimeout(timeoutId);
  }
 
  /**
   * Suspend showing the notification toasties.
   * @param {boolean} suspend Set to ``true`` to disable/hide toasties.
   */
  suspendToasties(suspend: boolean) {
    this.hideToasties = suspend;
  }
}