summaryrefslogtreecommitdiffstats
path: root/comm/mailnews/base/src/MailNotificationManager.jsm
blob: c16e37eb2fd23dc1bef47b9818c16f63b2691501 (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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const EXPORTED_SYMBOLS = ["MailNotificationManager"];

const { AppConstants } = ChromeUtils.importESModule(
  "resource://gre/modules/AppConstants.sys.mjs"
);
const { MailServices } = ChromeUtils.import(
  "resource:///modules/MailServices.jsm"
);
const { XPCOMUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/XPCOMUtils.sys.mjs"
);

const lazy = {};

XPCOMUtils.defineLazyModuleGetters(lazy, {
  MailUtils: "resource:///modules/MailUtils.jsm",
  WinUnreadBadge: "resource:///modules/WinUnreadBadge.jsm",
});

XPCOMUtils.defineLazyGetter(
  lazy,
  "l10n",
  () => new Localization(["messenger/messenger.ftl"])
);

/**
 * A module that listens to folder change events, and show notifications for new
 * mails if necessary.
 */
class MailNotificationManager {
  QueryInterface = ChromeUtils.generateQI([
    "nsIObserver",
    "nsIFolderListener",
    "mozINewMailListener",
  ]);

  constructor() {
    this._systemAlertAvailable = true;
    this._unreadChatCount = 0;
    this._unreadMailCount = 0;
    // @type {Map<nsIMsgFolder, number>} - A map of folder and its last biff time.
    this._folderBiffTime = new Map();
    // @type {Set<nsIMsgFolder>} - A set of folders to show alert for.
    this._pendingFolders = new Set();

    this._logger = console.createInstance({
      prefix: "mail.notification",
      maxLogLevel: "Warn",
      maxLogLevelPref: "mail.notification.loglevel",
    });
    this._bundle = Services.strings.createBundle(
      "chrome://messenger/locale/messenger.properties"
    );
    MailServices.mailSession.AddFolderListener(
      this,
      Ci.nsIFolderListener.intPropertyChanged
    );

    // Ensure that OS integration is defined before we attempt to initialize the
    // system tray icon.
    XPCOMUtils.defineLazyGetter(this, "_osIntegration", () => {
      try {
        return Cc["@mozilla.org/messenger/osintegration;1"].getService(
          Ci.nsIMessengerOSIntegration
        );
      } catch (e) {
        // We don't have OS integration on all platforms.
        return null;
      }
    });

    if (["macosx", "win"].includes(AppConstants.platform)) {
      // We don't have indicator for unread count on Linux yet.
      Cc["@mozilla.org/newMailNotificationService;1"]
        .getService(Ci.mozINewMailNotificationService)
        .addListener(this, Ci.mozINewMailNotificationService.count);

      Services.obs.addObserver(this, "unread-im-count-changed");
      Services.obs.addObserver(this, "profile-before-change");
    }

    if (AppConstants.platform == "macosx") {
      Services.obs.addObserver(this, "new-directed-incoming-message");
    }

    if (AppConstants.platform == "win") {
      Services.obs.addObserver(this, "windows-refresh-badge-tray");
      Services.prefs.addObserver("mail.biff.show_badge", this);
      Services.prefs.addObserver("mail.biff.show_tray_icon_always", this);
    }
  }

  observe(subject, topic, data) {
    switch (topic) {
      case "alertclickcallback":
        // Display the associated message when an alert is clicked.
        let msgHdr = Cc["@mozilla.org/messenger;1"]
          .getService(Ci.nsIMessenger)
          .msgHdrFromURI(data);
        lazy.MailUtils.displayMessageInFolderTab(msgHdr, true);
        return;
      case "unread-im-count-changed":
        this._logger.log(
          `Unread chat count changed to ${this._unreadChatCount}`
        );
        this._unreadChatCount = parseInt(data, 10) || 0;
        this._updateUnreadCount();
        return;
      case "new-directed-incoming-messenger":
        this._animateDockIcon();
        return;
      case "windows-refresh-badge-tray":
        this._updateUnreadCount();
        return;
      case "profile-before-change":
        this._osIntegration?.onExit();
        return;
      case "newmailalert-closed":
        // newmailalert.xhtml is closed, try to show the next queued folder.
        this._customizedAlertShown = false;
        this._showCustomizedAlert();
        return;
      case "nsPref:changed":
        if (
          data == "mail.biff.show_badge" ||
          data == "mail.biff.show_tray_icon_always"
        ) {
          this._updateUnreadCount();
        }
    }
  }

  /**
   * Following are nsIFolderListener interfaces. Do nothing about them.
   */
  onFolderAdded() {}
  onMessageAdded() {}
  onFolderRemoved() {}
  onMessageRemoved() {}
  onFolderPropertyChanged() {}
  /**
   * The only nsIFolderListener interface we care about.
   *
   * @see nsIFolderListener
   */
  onFolderIntPropertyChanged(folder, property, oldValue, newValue) {
    if (!Services.prefs.getBoolPref("mail.biff.show_alert")) {
      return;
    }

    this._logger.debug(
      `onFolderIntPropertyChanged; property=${property}: ${oldValue} => ${newValue}, folder.URI=${folder.URI}`
    );

    switch (property) {
      case "BiffState":
        if (newValue == Ci.nsIMsgFolder.nsMsgBiffState_NewMail) {
          // The folder argument is a root folder.
          this._fillAlertInfo(folder);
        }
        break;
      case "NewMailReceived":
        // The folder argument is a real folder.
        this._fillAlertInfo(folder);
        break;
    }
  }
  onFolderBoolPropertyChanged() {}
  onFolderUnicharPropertyChanged() {}
  onFolderPropertyFlagChanged() {}
  onFolderEvent() {}

  /**
   * @see mozINewMailNotificationService
   */
  onCountChanged(count) {
    this._logger.log(`Unread mail count changed to ${count}`);
    this._unreadMailCount = count;
    this._updateUnreadCount();
  }

  /**
   * Show an alert according to the changed folder.
   *
   * @param {nsIMsgFolder} changedFolder - The folder that emitted the change
   *   event, can be a root folder or a real folder.
   */
  async _fillAlertInfo(changedFolder) {
    let folder = this._getFirstRealFolderWithNewMail(changedFolder);
    if (!folder) {
      return;
    }

    let newMsgKeys = this._getNewMsgKeysNotNotified(folder);
    let numNewMessages = newMsgKeys.length;
    if (!numNewMessages) {
      return;
    }

    this._logger.debug(
      `Filling alert info; folder.URI=${folder.URI}, numNewMessages=${numNewMessages}`
    );
    let firstNewMsgHdr = folder.msgDatabase.getMsgHdrForKey(newMsgKeys[0]);

    let title = this._getAlertTitle(folder, numNewMessages);
    let body;
    try {
      body = await this._getAlertBody(folder, firstNewMsgHdr);
    } catch (e) {
      this._logger.error(e);
    }
    if (!title || !body) {
      return;
    }
    this._showAlert(firstNewMsgHdr, title, body);
    this._animateDockIcon();
  }

  /**
   * Iterate the subfolders of changedFolder, return the first real folder with
   * new mail.
   *
   * @param {nsIMsgFolder} changedFolder - The folder that emitted the change event.
   * @returns {nsIMsgFolder} The first real folder.
   */
  _getFirstRealFolderWithNewMail(changedFolder) {
    let folders = changedFolder.descendants;
    folders.unshift(changedFolder);

    for (let folder of folders) {
      let flags = folder.flags;
      if (
        !(flags & Ci.nsMsgFolderFlags.Inbox) &&
        flags & (Ci.nsMsgFolderFlags.SpecialUse | Ci.nsMsgFolderFlags.Virtual)
      ) {
        // Do not notify if the folder is not Inbox but one of
        // Drafts|Trash|SentMail|Templates|Junk|Archive|Queue or Virtual.
        continue;
      }

      if (folder.getNumNewMessages(false) > 0) {
        return folder;
      }
    }
    return null;
  }

  /**
   * Get the title for the alert.
   *
   * @param {nsIMsgFolder} folder - The changed folder.
   * @param {number} numNewMessages - The count of new messages.
   * @returns {string} The alert title.
   */
  _getAlertTitle(folder, numNewMessages) {
    return this._bundle.formatStringFromName(
      numNewMessages == 1
        ? "newMailNotification_message"
        : "newMailNotification_messages",
      [folder.server.prettyName, numNewMessages.toString()]
    );
  }

  /**
   * Get the body for the alert.
   *
   * @param {nsIMsgFolder} folder - The changed folder.
   * @param {nsIMsgHdr} msgHdr - The nsIMsgHdr of the first new messages.
   * @returns {string} The alert body.
   */
  async _getAlertBody(folder, msgHdr) {
    await new Promise((resolve, reject) => {
      let isAsync = folder.fetchMsgPreviewText([msgHdr.messageKey], {
        OnStartRunningUrl() {},
        // @see nsIUrlListener
        OnStopRunningUrl(url, exitCode) {
          Components.isSuccessCode(exitCode) ? resolve() : reject();
        },
      });
      if (!isAsync) {
        resolve();
      }
    });

    let alertBody = "";

    let subject = Services.prefs.getBoolPref("mail.biff.alert.show_subject")
      ? msgHdr.mime2DecodedSubject
      : "";
    let author = "";
    if (Services.prefs.getBoolPref("mail.biff.alert.show_sender")) {
      let addressObjects = MailServices.headerParser.makeFromDisplayAddress(
        msgHdr.mime2DecodedAuthor
      );
      let { name, email } = addressObjects[0] || {};
      author = name || email;
    }
    if (subject && author) {
      alertBody += this._bundle.formatStringFromName(
        "newMailNotification_messagetitle",
        [subject, author]
      );
    } else if (subject) {
      alertBody += subject;
    } else if (author) {
      alertBody += author;
    }
    let showPreview = Services.prefs.getBoolPref(
      "mail.biff.alert.show_preview"
    );
    if (showPreview) {
      let previewLength = Services.prefs.getIntPref(
        "mail.biff.alert.preview_length",
        40
      );
      let preview = msgHdr.getStringProperty("preview").slice(0, previewLength);
      if (preview) {
        alertBody += (alertBody ? "\n" : "") + preview;
      }
    }
    return alertBody;
  }

  /**
   * Show the alert.
   *
   * @param {nsIMsgHdr} msgHdr - The nsIMsgHdr of the first new messages.
   * @param {string} title - The alert title.
   * @param {string} body - The alert body.
   */
  _showAlert(msgHdr, title, body) {
    let folder = msgHdr.folder;

    // Try to use system alert first.
    if (
      Services.prefs.getBoolPref("mail.biff.use_system_alert", true) &&
      this._systemAlertAvailable
    ) {
      let alertsService = Cc["@mozilla.org/system-alerts-service;1"].getService(
        Ci.nsIAlertsService
      );
      let cookie = folder.generateMessageURI(msgHdr.messageKey);
      try {
        let alert = Cc["@mozilla.org/alert-notification;1"].createInstance(
          Ci.nsIAlertNotification
        );
        alert.init(
          cookie, // name
          "chrome://messenger/skin/icons/new-mail-alert.png",
          title,
          body,
          true, // clickable
          cookie
        );
        alertsService.showAlert(alert, this);
        return;
      } catch (e) {
        this._logger.error(e);
        this._systemAlertAvailable = false;
      }
    }

    // The use_system_alert pref is false or showAlert somehow failed, use the
    // customized alert window.
    this._showCustomizedAlert(folder);
  }

  /**
   * Show a customized alert window (newmailalert.xhtml), if there is already
   * one showing, do not show another one, because the newer one will block the
   * older one. Instead, save the folder and newMsgKeys to this._pendingFolders.
   *
   * @param {nsIMsgFolder} [folder] - The folder containing new messages.
   */
  _showCustomizedAlert(folder) {
    if (this._customizedAlertShown) {
      // Queue the folder.
      this._pendingFolders.add(folder);
      return;
    }
    if (!folder) {
      // Get the next folder from the queue.
      folder = this._pendingFolders.keys().next().value;
      if (!folder) {
        return;
      }
      this._pendingFolders.delete(folder);
    }

    let newMsgKeys = this._getNewMsgKeysNotNotified(folder);
    if (!newMsgKeys.length) {
      // No NEW message in the current folder, try the next queued folder.
      this._showCustomizedAlert();
      return;
    }

    let args = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
    args.appendElement(folder);
    args.appendElement({
      wrappedJSObject: newMsgKeys,
    });
    args.appendElement(this);
    Services.ww.openWindow(
      null,
      "chrome://messenger/content/newmailalert.xhtml",
      "_blank",
      "chrome,dialog=yes,titlebar=no,popup=yes",
      args
    );
    this._customizedAlertShown = true;
    this._folderBiffTime.set(folder, Date.now());
  }

  /**
   * Get all NEW messages from a folder that we received after last biff time.
   *
   * @param {nsIMsgFolder} folder - The message folder to check.
   * @returns {number[]} An array of message keys.
   */
  _getNewMsgKeysNotNotified(folder) {
    let msgDb = folder.msgDatabase;
    let lastBiffTime = this._folderBiffTime.get(folder) || 0;
    return msgDb
      .getNewList()
      .slice(-folder.getNumNewMessages(false))
      .filter(key => {
        let msgHdr = msgDb.getMsgHdrForKey(key);
        return msgHdr.dateInSeconds * 1000 > lastBiffTime;
      });
  }

  async _updateUnreadCount() {
    if (this._updatingUnreadCount) {
      // _updateUnreadCount can be triggered faster than we finish rendering the
      // badge. When that happens, set a flag and return.
      this._pendingUpdate = true;
      return;
    }
    this._updatingUnreadCount = true;

    this._logger.debug(
      `Update unreadMailCount=${this._unreadMailCount}, unreadChatCount=${this._unreadChatCount}`
    );
    let count = this._unreadMailCount + this._unreadChatCount;
    let tooltip = "";
    if (AppConstants.platform == "win") {
      if (!Services.prefs.getBoolPref("mail.biff.show_badge", true)) {
        count = 0;
      }
      if (count > 0) {
        tooltip = await lazy.l10n.formatValue("unread-messages-os-tooltip", {
          count,
        });
      }
      await lazy.WinUnreadBadge.updateUnreadCount(count, tooltip);
    }
    this._osIntegration?.updateUnreadCount(count, tooltip);

    this._updatingUnreadCount = false;
    if (this._pendingUpdate) {
      // There was at least one _updateUnreadCount call while we were rendering
      // the badge. Render one more time will ensure the badge reflects the
      // current state.
      this._pendingUpdate = false;
      this._updateUnreadCount();
    }
  }

  _animateDockIcon() {
    if (Services.prefs.getBoolPref("mail.biff.animate_dock_icon", false)) {
      Services.wm.getMostRecentWindow("mail:3pane")?.getAttention();
    }
  }
}