summaryrefslogtreecommitdiffstats
path: root/comm/chat/modules/OTRUI.sys.mjs
blob: fdf477160795451f1acc7c310db2fd70582ee1ae (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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
/* 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/. */

import { IMServices } from "resource:///modules/IMServices.sys.mjs";
import { OTR } from "resource:///modules/OTR.sys.mjs";
import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";

const lazy = {};

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

function _str(id) {
  return lazy.l10n.formatValueSync(id);
}

function _strArgs(id, args) {
  return lazy.l10n.formatValueSync(id, args);
}

const OTR_ADD_FINGER_DIALOG_URL =
  "chrome://chat/content/otr-add-fingerprint.xhtml";

const AUTH_STATUS_UNVERIFIED = "otr-auth-unverified";
var authLabelMap;
var trustMap;

function initStrings() {
  authLabelMap = new Map([
    ["otr:auth-error", _str("auth-error")],
    ["otr:auth-success", _str("auth-success")],
    ["otr:auth-success-them", _str("auth-success-them")],
    ["otr:auth-fail", _str("auth-fail")],
    ["otr:auth-waiting", _str("auth-waiting")],
  ]);

  let sl = _str("start-label");
  let al = _str("auth-label");
  let rfl = _str("refresh-label");
  let ral = _str("reauth-label");

  trustMap = new Map([
    [
      OTR.trustState.TRUST_NOT_PRIVATE,
      {
        startLabel: sl,
        authLabel: al,
        disableStart: false,
        disableEnd: true,
        disableAuth: true,
        class: "not-private",
      },
    ],
    [
      OTR.trustState.TRUST_UNVERIFIED,
      {
        startLabel: rfl,
        authLabel: al,
        disableStart: false,
        disableEnd: false,
        disableAuth: false,
        class: "unverified",
      },
    ],
    [
      OTR.trustState.TRUST_PRIVATE,
      {
        startLabel: rfl,
        authLabel: ral,
        disableStart: false,
        disableEnd: false,
        disableAuth: false,
        class: "private",
      },
    ],
    [
      OTR.trustState.TRUST_FINISHED,
      {
        startLabel: sl,
        authLabel: al,
        disableStart: false,
        disableEnd: false,
        disableAuth: true,
        class: "finished",
      },
    ],
  ]);
}

var windowRefs = new Map();

export var OTRUI = {
  enabled: false,
  stringsLoaded: false,
  globalDoc: null,
  visibleConv: null,

  debug: false,
  logMsg(msg) {
    if (!OTRUI.debug) {
      return;
    }
    Services.console.logStringMessage(msg);
  },

  addMenuObserver() {
    for (let win of Services.ww.getWindowEnumerator()) {
      OTRUI.addMenus(win);
    }
    Services.obs.addObserver(OTRUI, "domwindowopened");
  },

  removeMenuObserver() {
    for (let win of Services.ww.getWindowEnumerator()) {
      OTRUI.removeMenus(win);
    }
    Services.obs.removeObserver(OTRUI, "domwindowopened");
  },

  addMenus(win) {
    let doc = win.document;
    // Account for unready windows
    if (doc.readyState !== "complete") {
      let listen = function () {
        win.removeEventListener("load", listen);
        OTRUI.addMenus(win);
      };
      win.addEventListener("load", listen);
    }
  },

  removeMenus(win) {
    let doc = win.document;
    OTRUI.removeBuddyContextMenu(doc);
  },

  addBuddyContextMenu(buddyContextMenu, doc, contact) {
    if (!buddyContextMenu || !OTR.libLoaded) {
      return; // Not the buddy list context menu
    }

    let sep = doc.createXULElement("menuseparator");
    sep.setAttribute("id", "otrsep");
    let menuitem = doc.createXULElement("menuitem");
    menuitem.setAttribute("label", _str("buddycontextmenu-label"));
    menuitem.setAttribute("id", "otrcont");
    menuitem.addEventListener("command", () => {
      let args = OTRUI.contactWrapper(contact);
      args.wrappedJSObject = args;
      let features = "chrome,modal,centerscreen,resizable=no,minimizable=no";
      Services.ww.openWindow(
        null,
        OTR_ADD_FINGER_DIALOG_URL,
        "",
        features,
        args
      );
    });

    buddyContextMenu.addEventListener("popupshowing", e => {
      let target = e.target.triggerNode;
      if (target.localName == "richlistitem") {
        menuitem.hidden = false;
        sep.hidden = false;
      } else {
        /* probably imconv */
        menuitem.hidden = true;
        sep.hidden = true;
      }
    });

    buddyContextMenu.appendChild(sep);
    buddyContextMenu.appendChild(menuitem);
  },

  removeBuddyContextMenu(doc) {
    let s = doc.getElementById("otrsep");
    if (s) {
      s.remove();
    }
    let p = doc.getElementById("otrcont");
    if (p) {
      p.remove();
    }
  },

  loopKeyGenSuccess() {
    ChromeUtils.idleDispatch(OTRUI.genNextMissingKey);
  },

  loopKeyGenFailure(param) {
    ChromeUtils.idleDispatch(OTRUI.genNextMissingKey);
    OTRUI.reportKeyGenFailure(param);
  },

  reportKeyGenFailure(param) {
    throw new Error(_strArgs("otr-genkey-failed", { error: String(param) }));
  },

  accountsToGenKey: [],

  genNextMissingKey() {
    if (OTRUI.accountsToGenKey.length == 0) {
      return;
    }

    let acc = OTRUI.accountsToGenKey.pop();
    let fp = OTR.privateKeyFingerprint(acc.name, acc.prot);
    if (!fp) {
      OTR.generatePrivateKey(acc.name, acc.prot).then(
        OTRUI.loopKeyGenSuccess,
        OTRUI.loopKeyGenFailure
      );
    } else {
      ChromeUtils.idleDispatch(OTRUI.genNextMissingKey);
    }
  },

  genMissingKeys() {
    for (let acc of IMServices.accounts.getAccounts()) {
      OTRUI.accountsToGenKey.push({
        name: acc.normalizedName,
        prot: acc.protocol.normalizedName,
      });
    }
    ChromeUtils.idleDispatch(OTRUI.genNextMissingKey);
  },

  async init() {
    if (!OTRUI.stringsLoaded) {
      // HACK: calling initStrings may fail the first time due to synchronous
      // loading of the .ftl files. If we load the files and wait for a known
      // value asynchronously, no such failure will happen.
      //
      // If the value "start-label" is removed, this will fail.
      //
      // Also, we can't reuse this Localization object elsewhere because it
      // fails to load values synchronously (even after calling setIsSync).
      await new Localization(["messenger/otr/otrUI.ftl"]).formatValue(
        "start-label"
      );

      initStrings();
      OTRUI.stringsLoaded = true;
    }

    this.debug = Services.prefs.getBoolPref("chat.otr.trace", false);

    OTR.init({});
    if (!OTR.libLoaded) {
      return;
    }

    this.enabled = true;
    this.notificationbox = null;

    OTR.addObserver(OTRUI);
    OTR.loadFiles()
      .then(function () {
        Services.obs.addObserver(OTR, "new-ui-conversation");
        Services.obs.addObserver(OTR, "conversation-update-type");
        // Disabled until #76 is resolved.
        // Services.obs.addObserver(OTRUI, "contact-added", false);
        Services.obs.addObserver(OTRUI, "account-added");
        // Services.obs.addObserver(OTRUI, "contact-signed-off", false);
        Services.obs.addObserver(OTRUI, "conversation-loaded");
        Services.obs.addObserver(OTRUI, "conversation-closed");
        Services.obs.addObserver(OTRUI, "prpl-quit");

        for (let conv of IMServices.conversations.getConversations()) {
          OTRUI.initConv(conv);
        }
        OTRUI.addMenuObserver();

        ChromeUtils.idleDispatch(OTRUI.genMissingKeys);
      })
      .catch(function (err) {
        // console.log("===> " + err + "\n");
        throw err;
      });
  },

  disconnect(aConv) {
    if (aConv) {
      return OTR.disconnect(aConv, true);
    }
    let allGood = true;
    for (let conv of IMServices.conversations.getConversations()) {
      if (conv.isChat) {
        continue;
      }
      if (!OTR.disconnect(conv, true)) {
        allGood = false;
      }
    }
    return allGood;
  },

  openAuth(window, name, mode, uiConv, contactInfo) {
    let otrAuth = this.globalDoc.querySelector(".otr-auth");
    otrAuth.disabled = true;
    let win = window.openDialog(
      "chrome://chat/content/otr-auth.xhtml",
      "auth=" + name,
      "centerscreen,resizable=no,minimizable=no",
      mode,
      uiConv,
      contactInfo
    );
    windowRefs.set(name, win);
    window.addEventListener("beforeunload", function () {
      otrAuth.disabled = false;
      windowRefs.delete(name);
    });
  },

  closeAuth(context) {
    let win = windowRefs.get(context.username);
    if (win) {
      win.close();
    }
  },

  /**
   * Hide the encryption state container and any pending notifications.
   *
   * @param {Element} otrContainer
   * @param {Context} [context]
   */
  noOtrPossible(otrContainer, context) {
    otrContainer.hidden = true;

    if (context) {
      OTRUI.hideUserNotifications(context);
    } else {
      OTRUI.hideAllOTRNotifications();
    }
  },

  sendSystemAlert(uiConv, conv, bundleId) {
    uiConv.systemMessage(
      _strArgs(bundleId, { name: conv.normalizedName }),
      false,
      true
    );
  },

  setNotificationBox(notificationbox) {
    this.globalBox = notificationbox;
  },

  /*
   * These states are only relevant if OTR is the only encryption available for
   * the conversation. Protocol provided encryption takes priority.
   *  possible states:
   *    tab isn't a 1:1, isChat == true
   *      then OTR isn't possible, hide the button
   *    tab is a 1:1, isChat == false
   *      no conversation active, uiConv cannot be found
   *        then OTR isn't possible YET, hide the button
   *      conversation active, uiConv found
   *        disconnected?
   *          could the other side come back? should we keep the button?
   *        set the state based on the OTR library state
   */

  /**
   * Store a reference to the document, as well as the current conversation.
   *
   * @param {Element} aObject - conversation-browser instance (most importantly, has a _conv field)
   */
  addButton(aObject) {
    this.globalDoc = aObject.ownerDocument;
    let _conv = aObject._conv;
    OTRUI.visibleConv = _conv;
    if (
      _conv.encryptionState === Ci.prplIConversation.ENCRYPTION_NOT_SUPPORTED
    ) {
      OTRUI.setMsgState(_conv, null, this.globalDoc, true);
    }
  },

  /**
   * Hide the encryption state information for the current conversation.
   */
  hideOTRButton() {
    if (!OTR.libLoaded) {
      return;
    }
    if (!this.globalDoc) {
      return;
    }
    OTRUI.visibleConv = null;
    let otrContainer = this.globalDoc.querySelector(".encryption-container");
    OTRUI.noOtrPossible(otrContainer);
  },

  /**
   * Sets the visible conversation of the OTR UI state and ensures
   * the encryption state button is set up correctly.
   *
   * @param {prplIConversation} _conv
   */
  updateOTRButton(_conv) {
    if (
      _conv.encryptionState !== Ci.prplIConversation.ENCRYPTION_NOT_SUPPORTED
    ) {
      return;
    }
    if (!OTR.libLoaded) {
      return;
    }
    if (!this.globalDoc) {
      return;
    }
    OTRUI.visibleConv = _conv;
    let convBinding;
    for (let element of this.globalDoc.getElementById("conversationsBox")
      .children) {
      if (!element.hidden) {
        convBinding = element;
        break;
      }
    }
    if (convBinding && convBinding._conv && convBinding._conv.target) {
      OTRUI.setMsgState(_conv, null, this.globalDoc, false);
    } else {
      this.hideOTRButton();
    }
  },

  /**
   * Set encryption state on selector for conversation.
   *
   * @param {prplIConversation} _conv - Must match the visible conversation.
   * @param {Context} [context] - The OTR context for the conversation.
   * @param {DOMDocument} doc
   * @param {boolean} [addSystemMessage] - If a system message with the conversation security.
   */
  setMsgState(_conv, context, doc, addSystemMessage) {
    if (!this.visibleConv) {
      return;
    }
    if (_conv != null && !(_conv === this.visibleConv)) {
      return;
    }

    let otrContainer = doc.querySelector(".encryption-container");
    let otrButton = doc.querySelector(".encryption-button");
    if (_conv != null && _conv.isChat) {
      OTRUI.noOtrPossible(otrContainer, context);
      return;
    }

    if (!context && _conv != null) {
      context = OTR.getContext(_conv);
      if (!context) {
        OTRUI.noOtrPossible(otrContainer, null);
      }
    }

    try {
      let uiConv = OTR.getUIConvFromContext(context);
      if (uiConv != null && !(uiConv === this.visibleConv)) {
        return;
      }
      if (
        uiConv.encryptionState === Ci.prplIConversation.ENCRYPTION_ENABLED ||
        uiConv.encryptionState === Ci.prplIConversation.ENCRYPTION_TRUSTED
      ) {
        return;
      }

      if (uiConv.isChat) {
        OTRUI.noOtrPossible(otrContainer, context);
        return;
      }
      if (addSystemMessage) {
        let trust = OTRUI.getTrustSettings(context);
        let id = "state-" + trust.class;
        let msg;
        if (OTR.trust(context) == OTR.trustState.TRUST_NOT_PRIVATE) {
          msg = lazy.l10n.formatValueSync(id);
        } else {
          msg = lazy.l10n.formatValueSync(id, { name: context.username });
        }
        uiConv.systemMessage(msg, false, true);
      }
    } catch (e) {
      OTRUI.noOtrPossible(otrContainer, context);
      return;
    }

    otrContainer.hidden = false;
    let otrStart = doc.querySelector(".otr-start");
    let otrEnd = doc.querySelector(".otr-end");
    let otrAuth = doc.querySelector(".otr-auth");
    let trust = OTRUI.getTrustSettings(context);
    otrButton.setAttribute(
      "tooltiptext",
      _strArgs("state-" + trust.class, { name: context.username })
    );
    otrButton.setAttribute("label", _str("state-" + trust.class + "-label"));
    otrButton.className = "encryption-button encryption-" + trust.class;
    otrStart.setAttribute("label", trust.startLabel);
    otrStart.setAttribute("disabled", trust.disableStart);
    otrEnd.setAttribute("disabled", trust.disableEnd);
    otrAuth.setAttribute("label", trust.authLabel);
    otrAuth.setAttribute("disabled", trust.disableAuth);
    OTRUI.hideAllOTRNotifications();
    OTRUI.showUserNotifications(context);
  },

  alertTrust(context) {
    let uiConv = OTR.getUIConvFromContext(context);
    let trust = OTRUI.getTrustSettings(context);
    uiConv.systemMessage(
      _strArgs("afterauth-" + trust.class, { name: context.username }),
      false,
      true
    );
  },

  getTrustSettings(context) {
    let result = trustMap.get(OTR.trust(context));
    return result;
  },

  askAuth(aObject) {
    let uiConv = OTR.getUIConvFromContext(aObject.context);
    if (!uiConv) {
      return;
    }

    let name = uiConv.target.normalizedName;
    let msg = _strArgs("verify-request", { name });
    // Trigger the update of the unread message counter.
    uiConv.notifyVerifyOTR(msg);
    Services.obs.notifyObservers(uiConv, "new-otr-verification-request");

    let window = this.globalDoc.defaultView;
    let buttons = [
      {
        label: _str("finger-verify"),
        accessKey: _str("finger-verify-access-key"),
        callback() {
          OTRUI.openAuth(window, name, "ask", uiConv, aObject);
          // prevent closing of notification bar when the button is hit
          return true;
        },
      },
      {
        label: _str("finger-ignore"),
        accessKey: _str("finger-ignore-access-key"),
        callback() {
          let context = OTR.getContext(uiConv.target);
          OTR.abortSMP(context);
        },
      },
    ];

    let notification = this.globalBox.appendNotification(
      `ask-auth-${name}`,
      {
        label: msg,
        priority: this.globalBox.PRIORITY_WARNING_MEDIUM,
      },
      buttons
    );

    notification.removeAttribute("dismissable");
  },

  closeAskAuthNotification(aObject) {
    let name = aObject.context.username;
    let notification = this.globalBox.getNotificationWithValue(
      `ask-auth-${name}`
    );
    if (!notification) {
      return;
    }

    this.globalBox.removeNotification(notification);
  },

  closeUnverified(context) {
    let uiConv = OTR.getUIConvFromContext(context);
    if (!uiConv) {
      return;
    }

    for (let notification of this.globalBox.allNotifications) {
      if (
        context.username == notification.getAttribute("user") &&
        notification.getAttribute("value") == AUTH_STATUS_UNVERIFIED
      ) {
        notification.close();
      }
    }
  },

  hideUserNotifications(context) {
    for (let notification of this.globalBox.allNotifications) {
      if (context.username == notification.getAttribute("user")) {
        notification.close();
      }
    }
  },

  hideAllOTRNotifications() {
    for (let notification of this.globalBox.allNotifications) {
      if (notification.getAttribute("protocol") == "otr") {
        notification.setAttribute("hidden", "true");
      }
    }
  },

  showUserNotifications(context) {
    let name = context.username;
    for (let notification of this.globalBox.allNotifications) {
      if (name == notification.getAttribute("user")) {
        notification.removeAttribute("hidden");
      }
    }
  },

  notifyUnverified(context, seen) {
    let uiConv = OTR.getUIConvFromContext(context);
    if (!uiConv) {
      return;
    }

    let name = context.username;
    let window = this.globalDoc.defaultView;

    let buttons = [
      {
        label: _str("finger-verify"),
        accessKey: _str("finger-verify-access-key"),
        callback() {
          let name = uiConv.target.normalizedName;
          OTRUI.openAuth(window, name, "start", uiConv);
          // prevent closing of notification bar when the button is hit
          return true;
        },
      },
      {
        label: _str("finger-ignore"),
        accessKey: _str("finger-ignore-access-key"),
        callback() {
          let context = OTR.getContext(uiConv.target);
          OTR.abortSMP(context);
        },
      },
    ];

    let notification = this.globalBox.appendNotification(
      name,
      {
        label: _strArgs(`finger-${seen}`, { name }),
        priority: this.globalBox.PRIORITY_WARNING_MEDIUM,
      },
      buttons
    );

    // Set the user attribute so we can show and hide notifications based on the
    // currently viewed conversation.
    notification.setAttribute("user", name);
    // Set custom attributes for CSS styling.
    notification.setAttribute("protocol", "otr");
    notification.setAttribute("status", AUTH_STATUS_UNVERIFIED);
    // Prevent users from dismissing this notification.
    notification.removeAttribute("dismissable");

    if (!this.visibleConv) {
      return;
    }

    if (name !== this.visibleConv.normalizedName) {
      this.hideUserNotifications(context);
    }
  },

  closeVerification(context) {
    let uiConv = OTR.getUIConvFromContext(context);
    if (!uiConv) {
      return;
    }

    let prevNotification = OTRUI.globalBox.getNotificationWithValue(
      context.username
    );
    if (prevNotification) {
      prevNotification.close();
    }
  },

  notifyVerification(context, key, cancelable, verifiable) {
    let uiConv = OTR.getUIConvFromContext(context);
    if (!uiConv) {
      return;
    }

    OTRUI.closeVerification(context);

    let buttons = [];
    if (cancelable) {
      buttons = [
        {
          label: _str("auth-cancel"),
          accessKey: _str("auth-cancel-access-key"),
          callback() {
            let context = OTR.getContext(uiConv.target);
            OTR.abortSMP(context);
          },
        },
      ];
    }

    if (verifiable) {
      let window = this.globalDoc.defaultView;

      buttons = [
        {
          label: _str("finger-verify"),
          accessKey: _str("finger-verify-access-key"),
          callback() {
            let name = uiConv.target.normalizedName;
            OTRUI.openAuth(window, name, "start", uiConv);
            // prevent closing of notification bar when the button is hit
            return true;
          },
        },
        {
          label: _str("finger-ignore"),
          accessKey: _str("finger-ignore-access-key"),
          callback() {
            let context = OTR.getContext(uiConv.target);
            OTR.abortSMP(context);
          },
        },
      ];
    }

    // Change priority type based on the passed key.
    let priority = this.globalBox.PRIORITY_WARNING_HIGH;
    let dismissable = true;
    switch (key) {
      case "otr:auth-error":
      case "otr:auth-fail":
        priority = this.globalBox.PRIORITY_CRITICAL_HIGH;
        break;
      case "otr:auth-waiting":
        priority = this.globalBox.PRIORITY_INFO_MEDIUM;
        dismissable = false;
        break;

      default:
        break;
    }

    OTRUI.closeUnverified(context);
    let notification = this.globalBox.appendNotification(
      context.username,
      {
        label: authLabelMap.get(key),
        priority,
      },
      buttons
    );

    // Set the user attribute so we can show and hide notifications based on the
    // currently viewed conversation.
    notification.setAttribute("user", context.username);
    // Set custom attributes for CSS styling.
    notification.setAttribute("protocol", "otr");
    notification.setAttribute("status", key);

    // The notification API don't currently support a "success" PRIORITY flag,
    // so we need to manually set it if we need to.
    if (["otr:auth-success", "otr:auth-success-them"].includes(key)) {
      notification.setAttribute("type", "success");
    }

    if (!dismissable) {
      // Prevent users from dismissing this notification if something is in
      // progress or an action is required.
      notification.removeAttribute("dismissable");
    }
  },

  updateAuth(aObj) {
    // let uiConv = OTR.getUIConvFromContext(aObj.context);
    if (!aObj.progress) {
      OTRUI.closeAuth(aObj.context);
      OTRUI.notifyVerification(aObj.context, "otr:auth-error", false, false);
    } else if (aObj.progress === 100) {
      let key;
      let verifiable = false;
      if (aObj.success) {
        if (aObj.context.trust) {
          key = "otr:auth-success";
          OTR.notifyTrust(aObj.context);
        } else {
          key = "otr:auth-success-them";
          verifiable = true;
        }
      } else {
        key = "otr:auth-fail";
        if (!aObj.context.trust) {
          OTR.notifyTrust(aObj.context);
        }
      }
      OTRUI.notifyVerification(aObj.context, key, false, verifiable);
    } else {
      // TODO: show the aObj.progress to the user with a
      //   <progressmeter mode="determined" value="10" />
      OTRUI.notifyVerification(aObj.context, "otr:auth-waiting", true, false);
    }
    OTRUI.closeAskAuthNotification(aObj);
  },

  onAccountCreated(acc) {
    let account = acc.normalizedName;
    let protocol = acc.protocol.normalizedName;
    Promise.resolve();
    if (OTR.privateKeyFingerprint(account, protocol) === null) {
      OTR.generatePrivateKey(account, protocol).catch(
        OTRUI.reportKeyGenFailure
      );
    }
  },

  contactWrapper(contact) {
    // If the conversation already started.
    if (contact.buddy) {
      return {
        account: contact.buddy.normalizedName,
        protocol: contact.buddy.buddy.protocol.normalizedName,
        screenname: contact.buddy.userName,
      };
    }

    // For online and offline contacts without an open conversation.
    return {
      account:
        contact.preferredBuddy.preferredAccountBuddy.account.normalizedName,
      protocol: contact.preferredBuddy.protocol.normalizedName,
      screenname: contact.preferredBuddy.preferredAccountBuddy.userName,
    };
  },

  onContactAdded(contact) {
    let args = OTRUI.contactWrapper(contact);
    if (
      OTR.getFingerprintsForRecipient(
        args.account,
        args.protocol,
        args.screenname
      ).length > 0
    ) {
      return;
    }
    args.wrappedJSObject = args;
    let features = "chrome,modal,centerscreen,resizable=no,minimizable=no";
    Services.ww.openWindow(null, OTR_ADD_FINGER_DIALOG_URL, "", features, args);
  },

  observe(aObject, aTopic, aMsg) {
    let doc;
    // console.log("====> observing topic: " + aTopic + " with msg: " + aMsg);
    // console.log(aObject);

    switch (aTopic) {
      case "nsPref:changed":
        break;
      case "conversation-loaded":
        doc = aObject.ownerDocument;
        let windowtype = doc.documentElement.getAttribute("windowtype");
        if (windowtype !== "mail:3pane") {
          return;
        }
        OTRUI.addButton(aObject);
        break;
      case "conversation-closed":
        if (aObject.isChat) {
          return;
        }
        this.globalBox.removeAllNotifications();
        OTRUI.closeAuth(OTR.getContext(aObject));
        OTRUI.disconnect(aObject);
        break;
      // case "contact-signed-off":
      //  break;
      case "prpl-quit":
        OTRUI.disconnect(null);
        break;
      case "domwindowopened":
        OTRUI.addMenus(aObject);
        break;
      case "otr:generate": {
        let result = OTR.generatePrivateKeySync(
          aObject.account,
          aObject.protocol
        );
        if (result != null) {
          OTRUI.reportKeyGenFailure(result);
        }
        break;
      }
      case "otr:disconnected":
      case "otr:msg-state":
        if (
          aTopic === "otr:disconnected" ||
          OTR.trust(aObject) !== OTR.trustState.TRUST_UNVERIFIED
        ) {
          OTRUI.closeAuth(aObject);
          OTRUI.closeUnverified(aObject);
          OTRUI.closeVerification(aObject);
        }
        OTRUI.setMsgState(null, aObject, this.globalDoc, false);
        break;
      case "otr:unverified":
        if (!this.globalDoc) {
          let win = Services.wm.getMostRecentWindow("mail:3pane");
          if (!win) {
            return;
          }
          win.focus();
          win.showChatTab();
          this.globalDoc = win.document;
        }
        OTRUI.notifyUnverified(aObject, aMsg);
        break;
      case "otr:trust-state":
        OTRUI.alertTrust(aObject);
        break;
      case "otr:log":
        OTRUI.logMsg("otr: " + aObject);
        break;
      case "account-added":
        OTRUI.onAccountCreated(aObject);
        break;
      case "contact-added":
        OTRUI.onContactAdded(aObject);
        break;
      case "otr:auth-ask":
        OTRUI.askAuth(aObject);
        break;
      case "otr:auth-update":
        OTRUI.updateAuth(aObject);
        break;
      case "otr:cancel-ask-auth":
        OTRUI.closeAskAuthNotification(aObject);
        break;
    }
  },

  initConv(binding) {
    OTR.addConversation(binding._conv);
    OTRUI.addButton(binding);
  },

  /**
   * Restore the conversation to a state before OTR knew about it.
   *
   * @param {Element} binding - conversation-browser instance.
   */
  resetConv(binding) {
    OTR.removeConversation(binding._conv);
  },

  destroy() {
    if (!OTR.libLoaded) {
      return;
    }
    OTRUI.disconnect(null);
    Services.obs.removeObserver(OTR, "new-ui-conversation");
    Services.obs.removeObserver(OTR, "conversation-update-type");
    // Services.obs.removeObserver(OTRUI, "contact-added");
    // Services.obs.removeObserver(OTRUI, "contact-signed-off");
    Services.obs.removeObserver(OTRUI, "account-added");
    Services.obs.removeObserver(OTRUI, "conversation-loaded");
    Services.obs.removeObserver(OTRUI, "conversation-closed");
    Services.obs.removeObserver(OTRUI, "prpl-quit");

    for (let conv of IMServices.conversations.getConversations()) {
      OTRUI.resetConv(conv);
    }
    OTR.removeObserver(OTRUI);
    OTR.close();
    OTRUI.removeMenuObserver();
  },
};