summaryrefslogtreecommitdiffstats
path: root/comm/mail/components/im/content/imAccounts.js
blob: 46bb72c19716874897aac39cdd101867cb8c257d (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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
/* 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/. */

/* globals MozElements */
/* globals statusSelector */
/* globals MsgAccountManager */

var { DownloadUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/DownloadUtils.sys.mjs"
);

var { IMServices } = ChromeUtils.importESModule(
  "resource:///modules/IMServices.sys.mjs"
);
var { MailServices } = ChromeUtils.import(
  "resource:///modules/MailServices.jsm"
);
ChromeUtils.defineESModuleGetters(this, {
  PluralForm: "resource://gre/modules/PluralForm.sys.mjs",
});

// This is the list of notifications that the account manager window observes
var events = [
  "prpl-quit",
  "account-list-updated",
  "account-added",
  "account-updated",
  "account-removed",
  "account-connected",
  "account-connecting",
  "account-disconnected",
  "account-disconnecting",
  "account-connect-progress",
  "account-connect-error",
  "autologin-processed",
  "status-changed",
  "network:offline-status-changed",
];

var gAccountManager = {
  // Sets the delay after connect() or disconnect() during which
  // it is impossible to perform disconnect() and connect()
  _disabledDelay: 500,
  disableTimerID: 0,
  _connectedLabelInterval: 0,

  get msgNotificationBar() {
    if (!this._notificationBox) {
      this._notificationBox = new MozElements.NotificationBox(element => {
        document.getElementById("accounts-notification-box").prepend(element);
      });
    }
    return this._notificationBox;
  },

  load() {
    // Wait until the password service is ready before offering anything.
    Services.logins.initializationPromise.then(
      () => {
        this.accountList = document.getElementById("accountlist");
        let defaultID;
        IMServices.core.init(); // ensure the imCore is initialized.
        for (let acc of this.getAccounts()) {
          let elt = document.createXULElement("richlistitem", {
            is: "chat-account-richlistitem",
          });
          this.accountList.appendChild(elt);
          elt.build(acc);
          if (
            !defaultID &&
            acc.firstConnectionState == acc.FIRST_CONNECTION_CRASHED
          ) {
            defaultID = acc.id;
          }
        }
        for (let event of events) {
          Services.obs.addObserver(this, event);
        }
        if (!this.accountList.getRowCount()) {
          // This is horrible, but it works. Otherwise (at least on mac)
          // the wizard is not centered relatively to the account manager
          setTimeout(function () {
            gAccountManager.new();
          }, 0);
        } else {
          // we have accounts, show the list
          document.getElementById("noAccountScreen").hidden = true;
          document.getElementById("accounts-notification-box").hidden = false;

          // ensure an account is selected
          if (defaultID) {
            this.selectAccount(defaultID);
          } else {
            this.accountList.selectedIndex = 0;
          }
        }

        this.setAutoLoginNotification();

        this.accountList.addEventListener("keypress", this.onKeyPress, true);
        window.addEventListener("unload", this.unload.bind(this));
        this._connectedLabelInterval = setInterval(
          this.updateConnectedLabels,
          60000
        );
        statusSelector.init();
      },
      () => {
        this.close();
      }
    );
  },
  unload() {
    clearInterval(this._connectedLabelInterval);
    for (let event of events) {
      Services.obs.removeObserver(this, event);
    }
  },
  _updateAccountList() {
    let accountList = this.accountList;
    let i = 0;
    for (let acc of this.getAccounts()) {
      let oldItem = accountList.getItemAtIndex(i);
      if (oldItem.id != acc.id) {
        let accElt = document.getElementById(acc.id);
        accountList.insertBefore(accElt, oldItem);
        accElt.refreshState();
      }
      ++i;
    }

    if (accountList.itemCount == 0) {
      // Focus the "New Account" button if there are no accounts left.
      document.getElementById("newaccount").focus();
      // Return early, otherwise we'll run into an 'undefined property' strict
      //  warning when trying to focus the buttons. Fixes bug 408.
      return;
    }

    // The selected item is still selected
    if (accountList.selectedItem) {
      accountList.selectedItem.setFocus();
    }
    accountList.ensureSelectedElementIsVisible();

    // We need to refresh the disabled menu items
    this.disableCommandItems();
  },
  observe(aObject, aTopic, aData) {
    if (aTopic == "prpl-quit") {
      // libpurple is being uninitialized. We don't need the account
      // manager window anymore, close it.
      this.close();
      return;
    } else if (aTopic == "autologin-processed") {
      let notification =
        this.msgNotificationBar.getNotificationWithValue("autoLoginStatus");
      if (notification) {
        notification.close();
      }
      return;
    } else if (aTopic == "network:offline-status-changed") {
      this.setOffline(aData == "offline");
      return;
    } else if (aTopic == "status-changed") {
      this.setOffline(aObject.statusType == Ci.imIStatusInfo.STATUS_OFFLINE);
      return;
    } else if (aTopic == "account-list-updated") {
      this._updateAccountList();
      return;
    }

    // The following notification handlers need an account.
    let account = aObject.QueryInterface(Ci.imIAccount);

    if (aTopic == "account-added") {
      document.getElementById("noAccountScreen").hidden = true;
      document.getElementById("accounts-notification-box").hidden = false;
      let elt = document.createXULElement("richlistitem", {
        is: "chat-account-richlistitem",
      });
      this.accountList.appendChild(elt);
      elt.build(account);
      if (this.accountList.getRowCount() == 1) {
        this.accountList.selectedIndex = 0;
      }
    } else if (aTopic == "account-removed") {
      let elt = document.getElementById(account.id);
      elt.destroy();
      if (!elt.selected) {
        elt.remove();
        return;
      }
      // The currently selected element is removed,
      // ensure another element gets selected (if the list is not empty)
      var selectedIndex = this.accountList.selectedIndex;
      // Prevent errors if the timer is active and the account deleted
      clearTimeout(this.disableTimerID);
      this.disableTimerID = 0;
      elt.remove();
      var count = this.accountList.getRowCount();
      if (!count) {
        document.getElementById("noAccountScreen").hidden = false;
        document.getElementById("accounts-notification-box").hidden = true;
        return;
      }
      if (selectedIndex == count) {
        --selectedIndex;
      }
      this.accountList.selectedIndex = selectedIndex;
    } else if (aTopic == "account-updated") {
      document.getElementById(account.id).build(account);
      this.disableCommandItems();
    } else if (aTopic == "account-connect-progress") {
      document.getElementById(account.id).updateConnectingProgress();
    } else if (aTopic == "account-connect-error") {
      document.getElementById(account.id).updateConnectionError();
      // See NSSErrorsService::ErrorIsOverridable.
      if (
        [
          "MOZILLA_PKIX_ERROR_ADDITIONAL_POLICY_CONSTRAINT_FAILED",
          "MOZILLA_PKIX_ERROR_CA_CERT_USED_AS_END_ENTITY",
          "MOZILLA_PKIX_ERROR_EMPTY_ISSUER_NAME",
          "MOZILLA_PKIX_ERROR_INADEQUATE_KEY_SIZE",
          "MOZILLA_PKIX_ERROR_MITM_DETECTED",
          "MOZILLA_PKIX_ERROR_NOT_YET_VALID_CERTIFICATE",
          "MOZILLA_PKIX_ERROR_NOT_YET_VALID_ISSUER_CERTIFICATE",
          "MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT",
          "MOZILLA_PKIX_ERROR_V1_CERT_USED_AS_CA",
          "SEC_ERROR_CA_CERT_INVALID",
          "SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED",
          "SEC_ERROR_EXPIRED_CERTIFICATE",
          "SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE",
          "SEC_ERROR_INVALID_TIME",
          "SEC_ERROR_UNKNOWN_ISSUER",
          "SSL_ERROR_BAD_CERT_DOMAIN",
        ].includes(account.prplAccount.securityInfo?.errorCodeString)
      ) {
        this.addException();
      }
    } else {
      const stateEvents = {
        "account-connected": "connected",
        "account-connecting": "connecting",
        "account-disconnected": "disconnected",
        "account-disconnecting": "disconnecting",
      };
      if (aTopic in stateEvents) {
        let elt = document.getElementById(account.id);
        if (!elt) {
          // Probably disconnecting a removed account.
          return;
        }
        elt.refreshState(stateEvents[aTopic]);
      }
    }
  },
  cancelReconnection() {
    this.accountList.selectedItem.cancelReconnection();
  },
  connect() {
    let account = this.accountList.selectedItem.account;
    if (account.disconnected) {
      this.temporarilyDisableButtons();
      account.connect();
    }
  },
  disconnect() {
    let account = this.accountList.selectedItem.account;
    if (account.connected || account.connecting) {
      this.temporarilyDisableButtons();
      account.disconnect();
    }
  },
  addException() {
    let account = this.accountList.selectedItem.account;
    let prplAccount = account.prplAccount;
    if (!prplAccount.connectionTarget) {
      return;
    }

    // Open the Gecko SSL exception dialog.
    let params = {
      exceptionAdded: false,
      securityInfo: prplAccount.securityInfo,
      prefetchCert: true,
      location: prplAccount.connectionTarget,
    };
    window.openDialog(
      "chrome://pippki/content/exceptionDialog.xhtml",
      "",
      "chrome,centerscreen,modal",
      params
    );
    // Reconnect the account if an exception was added.
    if (params.exceptionAdded) {
      account.disconnect();
      account.connect();
    }
  },
  copyDebugLog() {
    let account = this.accountList.selectedItem.account;
    let text = account
      .getDebugMessages()
      .map(function (dbgMsg) {
        let m = dbgMsg.message;
        let time = new Date(m.timeStamp);
        const dateTimeFormatter = new Services.intl.DateTimeFormat(undefined, {
          dateStyle: "short",
          timeStyle: "long",
        });
        time = dateTimeFormatter.format(time);
        let level = dbgMsg.logLevel;
        if (!level) {
          return "(" + m.errorMessage + ")";
        }
        if (level == dbgMsg.LEVEL_ERROR) {
          level = "ERROR";
        } else if (level == dbgMsg.LEVEL_WARNING) {
          level = "WARN.";
        } else if (level == dbgMsg.LEVEL_LOG) {
          level = "LOG  ";
        } else {
          level = "DEBUG";
        }
        return (
          "[" +
          time +
          "] " +
          level +
          " (@ " +
          m.sourceLine +
          " " +
          m.sourceName +
          ":" +
          m.lineNumber +
          ")\n" +
          m.errorMessage
        );
      })
      .join("\n");
    Cc["@mozilla.org/widget/clipboardhelper;1"]
      .getService(Ci.nsIClipboardHelper)
      .copyString(text);
  },
  updateConnectedLabels() {
    for (let i = 0; i < gAccountManager.accountList.itemCount; ++i) {
      let item = gAccountManager.accountList.getItemAtIndex(i);
      if (item.account.connected) {
        item.refreshConnectedLabel();
      }
    }
  },
  /* This function disables the connect/disconnect buttons for
   * `this._disabledDelay` ms before calling disableCommandItems to restore
   * the state of the buttons.
   */
  temporarilyDisableButtons() {
    document.getElementById("cmd_disconnect").setAttribute("disabled", "true");
    document.getElementById("cmd_connect").setAttribute("disabled", "true");
    clearTimeout(this.disableTimerID);
    this.accountList.focus();
    this.disableTimerID = setTimeout(
      function (aItem) {
        gAccountManager.disableTimerID = 0;
        gAccountManager.disableCommandItems();
        aItem.setFocus();
      },
      this._disabledDelay,
      this.accountList.selectedItem
    );
  },

  new() {
    this.openDialog("chrome://messenger/content/chat/imAccountWizard.xhtml");
  },
  edit() {
    // Find the nsIIncomingServer for the current imIAccount.
    let server = null;
    let imAccountId = this.accountList.selectedItem.account.numericId;
    for (let account of MailServices.accounts.accounts) {
      let incomingServer = account.incomingServer;
      if (!incomingServer || incomingServer.type != "im") {
        continue;
      }
      if (incomingServer.wrappedJSObject.imAccount.numericId == imAccountId) {
        server = incomingServer;
        break;
      }
    }

    MsgAccountManager(null, server);
  },
  autologin() {
    var elt = this.accountList.selectedItem;
    elt.autoLogin = !elt.autoLogin;
  },
  close() {
    // If a modal dialog is opened, we can't close this window now
    if (this.modalDialog) {
      setTimeout(function () {
        window.close();
      }, 0);
    } else {
      window.close();
    }
  },

  /* This function disables or enables the currently selected button and
     the corresponding context menu item */
  disableCommandItems() {
    let accountList = this.accountList;
    let selectedItem = accountList.selectedItem;
    // When opening the account manager, if accounts have errors, we
    // can be called during build(), before any item is selected.
    // In this case, just return early.
    if (!selectedItem) {
      return;
    }

    // If the timer that disables the button (for a short time) already exists,
    // we don't want to interfere and set the button as enabled.
    if (this.disableTimerID) {
      return;
    }

    let account = selectedItem.account;
    let isCommandDisabled =
      this.isOffline ||
      (account.disconnected &&
        account.connectionErrorReason == Ci.imIAccount.ERROR_UNKNOWN_PRPL);

    let disabledItems = ["connect", "disconnect"];
    for (let name of disabledItems) {
      let elt = document.getElementById("cmd_" + name);
      if (isCommandDisabled) {
        elt.setAttribute("disabled", "true");
      } else {
        elt.removeAttribute("disabled");
      }
    }
  },
  onContextMenuShowing(event) {
    let targetElt = event.target.triggerNode.closest(
      'richlistitem[is="chat-account-richlistitem"]'
    );
    document.querySelectorAll(".im-context-account-item").forEach(e => {
      e.hidden = !targetElt;
    });
    if (targetElt) {
      let account = targetElt.account;
      let hiddenItems = {
        connect: !account.disconnected,
        disconnect: account.disconnected || account.disconnecting,
        cancelReconnection: !targetElt.hasAttribute("reconnectPending"),
        accountsItemsSeparator: account.disconnecting,
      };
      for (let name in hiddenItems) {
        document.getElementById("context_" + name).hidden = hiddenItems[name];
      }
    }
  },

  selectAccount(aAccountId) {
    this.accountList.selectedItem = document.getElementById(aAccountId);
    this.accountList.ensureSelectedElementIsVisible();
  },
  onAccountSelect() {
    clearTimeout(this.disableTimerID);
    this.disableTimerID = 0;
    this.disableCommandItems();
    // Horrible hack here too, see Bug 177
    setTimeout(
      function (aThis) {
        try {
          aThis.accountList.selectedItem.setFocus();
        } catch (e) {
          /* Sometimes if the user goes too fast with VK_UP or VK_DOWN, the
           selectedItem doesn't have the expected binding attached */
        }
      },
      0,
      this
    );
  },

  onKeyPress(event) {
    if (!this.selectedItem) {
      return;
    }
    // As we stop propagation, the default action applies to the richlistbox
    // so that the selected account is changed with this default action
    if (event.keyCode == event.DOM_VK_DOWN) {
      if (this.selectedIndex < this.itemCount - 1) {
        this.ensureIndexIsVisible(this.selectedIndex + 1);
      }
      event.stopPropagation();
      return;
    }

    if (event.keyCode == event.DOM_VK_UP) {
      if (this.selectedIndex > 0) {
        this.ensureIndexIsVisible(this.selectedIndex - 1);
      }
      event.stopPropagation();
      return;
    }

    if (event.keyCode == event.DOM_VK_RETURN) {
      let target = event.target;
      if (
        target.localName != "checkbox" &&
        (target.localName != "button" ||
          /^(dis)?connect$/.test(target.getAttribute("anonid")))
      ) {
        this.selectedItem.buttons.proceedDefaultAction();
      }
    }
  },

  *getAccounts() {
    for (let account of IMServices.accounts.getAccounts()) {
      yield account;
    }
  },

  openDialog(aUrl, aArgs) {
    this.modalDialog = true;
    window.openDialog(aUrl, "", "chrome,modal,titlebar,centerscreen", aArgs);
    this.modalDialog = false;
  },

  setAutoLoginNotification() {
    var as = IMServices.accounts;
    var autoLoginStatus = as.autoLoginStatus;
    let isOffline = false;
    let crashCount = 0;
    for (let acc of this.getAccounts()) {
      if (
        acc.autoLogin &&
        acc.firstConnectionState == acc.FIRST_CONNECTION_CRASHED
      ) {
        ++crashCount;
      }
    }

    if (autoLoginStatus == as.AUTOLOGIN_ENABLED && crashCount == 0) {
      let status = IMServices.core.globalUserStatus.statusType;
      this.setOffline(isOffline || status == Ci.imIStatusInfo.STATUS_OFFLINE);
      return;
    }

    var bundle = document.getElementById("accountsBundle");
    let box = this.msgNotificationBar;
    var prio = box.PRIORITY_INFO_HIGH;
    var connectNowButton = {
      accessKey: bundle.getString(
        "accountsManager.notification.button.accessKey"
      ),
      callback: this.processAutoLogin,
      label: bundle.getString("accountsManager.notification.button.label"),
    };
    var barLabel;

    switch (autoLoginStatus) {
      case as.AUTOLOGIN_USER_DISABLED:
        barLabel = bundle.getString(
          "accountsManager.notification.userDisabled.label"
        );
        break;

      case as.AUTOLOGIN_SAFE_MODE:
        barLabel = bundle.getString(
          "accountsManager.notification.safeMode.label"
        );
        break;

      case as.AUTOLOGIN_START_OFFLINE:
        barLabel = bundle.getString(
          "accountsManager.notification.startOffline.label"
        );
        isOffline = true;
        break;

      case as.AUTOLOGIN_CRASH:
        barLabel = bundle.getString("accountsManager.notification.crash.label");
        prio = box.PRIORITY_WARNING_MEDIUM;
        break;

      /* One or more accounts made the application crash during their connection.
         If none, this function has already returned */
      case as.AUTOLOGIN_ENABLED:
        barLabel = bundle.getString(
          "accountsManager.notification.singleCrash.label"
        );
        barLabel = PluralForm.get(crashCount, barLabel).replace(
          "#1",
          crashCount
        );
        prio = box.PRIORITY_WARNING_MEDIUM;
        connectNowButton.callback = this.processCrashedAccountsLogin;
        break;

      default:
        barLabel = bundle.getString("accountsManager.notification.other.label");
    }
    let status = IMServices.core.globalUserStatus.statusType;
    this.setOffline(isOffline || status == Ci.imIStatusInfo.STATUS_OFFLINE);

    box.appendNotification(
      "autologinStatus",
      {
        label: barLabel,
        priority: prio,
      },
      [connectNowButton]
    );
  },
  processAutoLogin() {
    var ioService = Services.io;
    if (ioService.offline) {
      ioService.manageOfflineStatus = false;
      ioService.offline = false;
    }

    IMServices.accounts.processAutoLogin();

    gAccountManager.accountList.selectedItem.setFocus();
  },
  processCrashedAccountsLogin() {
    for (let acc in gAccountManager.getAccounts()) {
      if (
        acc.disconnected &&
        acc.autoLogin &&
        acc.firstConnectionState == acc.FIRST_CONNECTION_CRASHED
      ) {
        acc.connect();
      }
    }

    let notification =
      this.msgNotificationBar.getNotificationWithValue("autoLoginStatus");
    if (notification) {
      notification.close();
    }

    gAccountManager.accountList.selectedItem.setFocus();
  },
  setOffline(aState) {
    this.isOffline = aState;
    if (aState) {
      this.accountList.setAttribute("offline", "true");
    } else {
      this.accountList.removeAttribute("offline");
    }
    this.disableCommandItems();
  },
};

window.addEventListener("DOMContentLoaded", () => {
  gAccountManager.load();
});