Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Notification.ts « src - github.com/jsxc/jsxc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 2daaa55b4b794cc96481013317ca1679aa572fbd (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
211
212
213
import { IContact } from './Contact.interface';
import Translation from './util/Translation';
import Client from './Client';
import * as CONST from './CONST';
import { FUNCTION as NOTICEFUNCTION } from './Notice';
import openConfirmDialog from './ui/dialogs/confirm';
import Overlay from './ui/Overlay';
import Hash from './util/Hash';
import Log from './util/Log';
import defaultIconFile = require('../images/XMPP_logo.png');
import { Presence } from './connection/AbstractConnection';

interface INotificationSettings {
   title: string;
   message: string;
   duration?: number;
   force?: boolean;
   soundFile?: string;
   loop?: boolean;
   source?: IContact;
   icon?: string;
}

enum NotificationState {
   DISABLED,
   ENABLED,
   ASK,
}

let NotificationAPI = (<any>window).Notification;

export default class Notification {
   private static popupDelay = 1000;

   private static audioObject;

   public static askForPermission() {
      let overlay = new Overlay();
      openConfirmDialog(Translation.t('Should_we_notify_you_'))
         .getPromise()
         .then(a => {
            overlay.open();

            return Notification.requestPermission();
         })
         .then(() => {
            Client.getStorage().setItem('notificationState', NotificationState.ENABLED);
         })
         .catch(err => {
            Client.getStorage().setItem('notificationState', NotificationState.DISABLED);
         })
         .then(() => {
            overlay.close();
         });
   }

   public static async notify(settings: INotificationSettings) {
      if (typeof NotificationAPI === 'undefined') {
         Log.debug('Drop notification, because notification API not available');

         return;
      }

      if (!Notification.getOption('enable')) {
         Log.debug('Drop notification, because notifications are disabled.');

         return; // notifications disabled
      }

      let state = Client.getStorage().getItem('notificationState');
      state = typeof state === 'number' ? state : NotificationState.ASK;

      if (state === NotificationState.ASK && !Notification.hasPermission()) {
         Client.getNoticeManager().addNotice({
            title: Translation.t('Notifications') + '?',
            description: Translation.t('Should_we_notify_you_'),
            fnName: NOTICEFUNCTION.notificationRequest,
         });
      }

      if (!Notification.hasPermission()) {
         Log.debug('Drop notification, because I have no permission');

         return;
      }

      if (Client.isVisible() && !settings.force) {
         Log.debug('Drop notification, because client is visible.');

         return;
      }

      settings.icon = settings.icon || <string>(<any>defaultIconFile);

      if (settings.source) {
         let avatar;

         try {
            avatar = await settings.source.getAvatar();
         } catch (err) {}

         if (avatar && avatar.src) {
            settings.icon = avatar.src;
         } else {
            let hash = Hash.String(settings.source.getName());

            let hue = Math.abs(hash) % 360;
            let saturation = 90;
            let lightness = 65;

            let canvas = <HTMLCanvasElement>$('<canvas>').get(0);
            canvas.height = 100;
            canvas.width = 100;

            let ctx = canvas.getContext('2d');

            ctx.fillStyle = 'hsl(' + hue + ', ' + saturation + '%, ' + lightness + '%)';
            ctx.fillRect(0, 0, 100, 100);

            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillStyle = 'white';
            ctx.font = 'bold 50px sans-serif';
            ctx.fillText(settings.source.getName()[0].toUpperCase(), 50, 50);

            settings.icon = canvas.toDataURL('image/jpeg');
         }
      }

      settings.duration = settings.duration || Notification.getOption('popupDuration');

      setTimeout(function () {
         Notification.showPopup(settings);
      }, Notification.popupDelay);
   }

   private static showPopup(settings: INotificationSettings) {
      if (typeof settings.soundFile === 'string') {
         Notification.playSound(settings.soundFile, settings.loop, settings.force);
      }

      let popup = new NotificationAPI(settings.title, {
         body: settings.message,
         icon: settings.icon,
      });

      if (settings.duration > 0) {
         setTimeout(function () {
            popup.close();
         }, settings.duration);
      }
   }

   private static requestPermission() {
      return new Promise<void>((resolve, reject) => {
         NotificationAPI.requestPermission(function (status) {
            if (NotificationAPI.permission !== status) {
               NotificationAPI.permission = status;
            }

            if (Notification.hasPermission()) {
               resolve();
            } else {
               reject();
            }
         });
      });
   }

   private static hasPermission() {
      return NotificationAPI.permission === CONST.NOTIFICATION_GRANTED;
   }

   public static playSound(soundFile: string, loop?: boolean, force?: boolean) {
      if (Notification.getOption('mute') || Client.getPresenceController().getCurrentPresence() === Presence.dnd) {
         Log.debug('Sound is muted or presence is DND');

         return;
      }

      if (Client.isVisible() && !force) {
         return;
      }

      Notification.stopSound();

      let audio = new Audio(soundFile);
      audio.loop = loop || false;
      audio
         .play()
         .then(() => {
            Notification.audioObject = audio;
         })
         .catch(err => {
            Log.debug('Audio error', err);
         });
   }

   public static stopSound() {
      let audio = Notification.audioObject;

      if (typeof audio !== 'undefined' && audio !== null) {
         audio.pause();
         Notification.audioObject = null;
      }
   }

   private static getOption(name: string): any {
      let options = Client.getOption('notification') || {};

      return options[name];
   }
}