summaryrefslogtreecommitdiffhomepage
path: root/gui/src/main/notification-controller.ts
blob: c4816e796abb92eb29510e3f478a2a6deec6b994 (plain)
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import { app, nativeImage, NativeImage, Notification } from 'electron';
import os from 'os';
import path from 'path';
import { TunnelState } from '../shared/daemon-rpc-types';
import log from '../shared/logging';
import {
  ConnectedNotificationProvider,
  ConnectingNotificationProvider,
  DisconnectedNotificationProvider,
  ErrorNotificationProvider,
  NotificationAction,
  ReconnectingNotificationProvider,
  SystemNotification,
  SystemNotificationProvider,
} from '../shared/notifications/notification';

interface NotificationControllerDelegate {
  openApp(): void;
  openLink(url: string, withAuth?: boolean): Promise<void>;
  isWindowVisible(): boolean;
  areSystemNotificationsEnabled(): boolean;
}

export default class NotificationController {
  private lastTunnelStateAnnouncement?: { body: string; notification: Notification };
  private reconnecting = false;
  private presentedNotifications: { [key: string]: boolean } = {};
  private pendingNotifications: Notification[] = [];
  private notificationTitle = process.platform === 'linux' ? app.name : '';
  private notificationIcon?: NativeImage;

  constructor(private notificationControllerDelegate: NotificationControllerDelegate) {
    let usePngIcon;
    if (process.platform === 'linux') {
      usePngIcon = true;
    } else if (process.platform === 'win32') {
      usePngIcon = parseInt(os.release().split('.')[0], 10) >= 10;
    } else {
      usePngIcon = false;
    }

    if (usePngIcon) {
      const basePath = path.resolve(path.join(__dirname, '../../assets/images'));
      this.notificationIcon = nativeImage.createFromPath(
        path.join(basePath, 'icon-notification.png'),
      );
    }
  }

  public notifyTunnelState(
    tunnelState: TunnelState,
    blockWhenDisconnected: boolean,
    hasExcludedApps: boolean,
    accountExpiry?: string,
  ) {
    const notificationProviders: SystemNotificationProvider[] = [
      new ConnectingNotificationProvider({ tunnelState, reconnecting: this.reconnecting }),
      new ConnectedNotificationProvider(tunnelState),
      new ReconnectingNotificationProvider(tunnelState),
      new DisconnectedNotificationProvider({ tunnelState, blockWhenDisconnected }),
      new ErrorNotificationProvider({ tunnelState, accountExpiry, hasExcludedApps }),
    ];

    const notificationProvider = notificationProviders.find((notification) =>
      notification.mayDisplay(),
    );

    if (notificationProvider) {
      const notification = notificationProvider.getSystemNotification();

      if (notification) {
        this.showTunnelStateNotification(notification);
      } else {
        log.error(
          `Notification providers mayDisplay() returned true but getSystemNotification() returned undefined for ${notificationProvider.constructor.name}`,
        );
      }
    }

    this.reconnecting =
      tunnelState.state === 'disconnecting' && tunnelState.details === 'reconnect';
  }

  public cancelPendingNotifications() {
    for (const notification of this.pendingNotifications) {
      notification.close();
    }
  }

  public resetTunnelStateAnnouncements() {
    this.lastTunnelStateAnnouncement = undefined;
  }

  public notify(systemNotification: SystemNotification) {
    if (this.evaluateNotification(systemNotification)) {
      const notification = this.createNotification(systemNotification);
      this.addPendingNotification(notification);
      notification.show();

      if (!systemNotification.critical) {
        setTimeout(() => notification.close(), 4000);
      }

      return notification;
    } else {
      return;
    }
  }

  private createNotification(systemNotification: SystemNotification) {
    const notification = new Notification({
      title: this.notificationTitle,
      body: systemNotification.message,
      silent: true,
      icon: this.notificationIcon,
      timeoutType: systemNotification.critical ? 'never' : 'default',
    });

    // Action buttons are only available on macOS.
    if (process.platform === 'darwin') {
      if (systemNotification.action) {
        notification.actions = [{ type: 'button', text: systemNotification.action.text }];
        notification.on('action', () => this.performAction(systemNotification.action));
      }
      notification.on('click', () => this.notificationControllerDelegate.openApp());
    } else if (!(process.platform === 'win32' && systemNotification.critical)) {
      if (systemNotification.action) {
        notification.on('click', () => this.performAction(systemNotification.action));
      } else {
        notification.on('click', () => this.notificationControllerDelegate.openApp());
      }
    }

    return notification;
  }

  private performAction(action?: NotificationAction) {
    if (action && action.type === 'open-url') {
      void this.notificationControllerDelegate.openLink(action.url, action.withAuth);
    }
  }

  private showTunnelStateNotification(systemNotification: SystemNotification) {
    const message = systemNotification.message;
    const lastAnnouncement = this.lastTunnelStateAnnouncement;
    const sameAsLastNotification = lastAnnouncement && lastAnnouncement.body === message;

    if (sameAsLastNotification) {
      return;
    }

    if (lastAnnouncement) {
      lastAnnouncement.notification.close();
    }

    const newNotification = this.notify(systemNotification);

    if (newNotification) {
      this.lastTunnelStateAnnouncement = {
        body: message,
        notification: newNotification,
      };
    }
  }

  private addPendingNotification(notification: Notification) {
    notification.on('close', () => {
      this.removePendingNotification(notification);
    });

    this.pendingNotifications.push(notification);
  }

  private removePendingNotification(notification: Notification) {
    const index = this.pendingNotifications.indexOf(notification);
    if (index !== -1) {
      this.pendingNotifications.splice(index, 1);
    }
  }

  private evaluateNotification(notification: SystemNotification) {
    const suppressDueToDevelopment =
      notification.suppressInDevelopment && process.env.NODE_ENV === 'development';
    const suppressDueToVisibleWindow = this.notificationControllerDelegate.isWindowVisible();
    const suppressDueToPreference =
      !this.notificationControllerDelegate.areSystemNotificationsEnabled() &&
      !notification.critical;

    return (
      !suppressDueToDevelopment &&
      !suppressDueToVisibleWindow &&
      !suppressDueToPreference &&
      !this.suppressDueToAlreadyPresented(notification)
    );
  }

  private suppressDueToAlreadyPresented(notification: SystemNotification) {
    const presented = this.presentedNotifications;
    if (notification.presentOnce?.value) {
      if (presented[notification.presentOnce.name]) {
        return true;
      } else {
        presented[notification.presentOnce.name] = true;
        return false;
      }
    } else {
      return false;
    }
  }
}