ui.py 20.3 KB
Newer Older
Philipp Hörist's avatar
Philipp Hörist committed
1
# -*- coding: utf-8 -*-
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

'''
Copyright 2015 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
Copyright 2015 Daniel Gultsch <daniel@cgultsch.de>
Copyright 2016 Philipp Hörist <philipp@hoerist.com>

This file is part of Gajim-OMEMO plugin.

The Gajim-OMEMO plugin is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.

Gajim-OMEMO is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
the Gajim-OMEMO plugin.  If not, see <http://www.gnu.org/licenses/>.
'''
Philipp Hörist's avatar
Philipp Hörist committed
22
23
24

import binascii
import logging
25
import os
26
from enum import IntEnum, unique
Philipp Hörist's avatar
Philipp Hörist committed
27

28
from gi.repository import Gtk, GdkPixbuf, Gdk
29
from axolotl.state.sessionrecord import SessionRecord
Philipp Hörist's avatar
Philipp Hörist committed
30
31
32

log = logging.getLogger('gajim.plugin_system.omemo')

33
34
35
36
PILLOW = False
try:
    import qrcode
    PILLOW = True
37
38
39
except ImportError as error:
    log.debug(error)
    log.error('python-qrcode or dependencies of it are not available')
40

41
42
43
44
from gajim.common import app
from gajim.common import configpaths
from gajim.dialogs import YesNoDialog
from gajim.plugins.gui import GajimPluginConfigDialog
Philipp Hörist's avatar
Philipp Hörist committed
45
46


47
48
49
50
51
@unique
class State(IntEnum):
    UNTRUSTED = 0
    TRUSTED = 1
    UNDECIDED = 2
Philipp Hörist's avatar
Philipp Hörist committed
52
53
54
55
56
57
58
59
60
61
62


class OMEMOConfigDialog(GajimPluginConfigDialog):
    def init(self):
        # pylint: disable=attribute-defined-outside-init
        self.GTK_BUILDER_FILE_PATH = \
            self.plugin.local_file_path('config_dialog.ui')
        self.B = Gtk.Builder()
        self.B.set_translation_domain('gajim_plugins')
        self.B.add_from_file(self.GTK_BUILDER_FILE_PATH)

63
64
65
66
67
        try:
            self.disabled_accounts = self.plugin.config['DISABLED_ACCOUNTS']
        except KeyError:
            self.plugin.config['DISABLED_ACCOUNTS'] = []
            self.disabled_accounts = self.plugin.config['DISABLED_ACCOUNTS']
Philipp Hörist's avatar
Philipp Hörist committed
68

69
70
        log.debug('Disabled Accounts:')
        log.debug(self.disabled_accounts)
Philipp Hörist's avatar
Philipp Hörist committed
71

72
73
        self.fpr_model = self.B.get_object('fingerprint_store')
        self.device_model = self.B.get_object('deviceid_store')
Philipp Hörist's avatar
Philipp Hörist committed
74
75
76

        self.fpr_view = self.B.get_object('fingerprint_view')

77
78
        self.disabled_acc_store = self.B.get_object('disabled_account_store')
        self.account_store = self.B.get_object('account_store')
Philipp Hörist's avatar
Philipp Hörist committed
79

80
81
        self.active_acc_view = self.B.get_object('active_accounts_view')
        self.disabled_acc_view = self.B.get_object('disabled_accounts_view')
Philipp Hörist's avatar
Philipp Hörist committed
82
83
84
85
86
87

        vbox = self.get_content_area()
        vbox.pack_start(self.B.get_object('notebook1'), True, True, 0)

        self.B.connect_signals(self)

88
89
        self.plugin_active = False

Philipp Hörist's avatar
Philipp Hörist committed
90
    def on_run(self):
91
        for plugin in app.plugin_manager.active_plugins:
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
            log.debug(type(plugin))
            if type(plugin).__name__ == 'OmemoPlugin':
                self.plugin_active = True
                break
        self.update_account_store()
        self.update_account_combobox()
        self.update_disabled_account_view()

    def is_in_accountstore(self, account):
        for row in self.account_store:
            if row[0] == account:
                return True
        return False

    def update_account_store(self):
107
        for account in sorted(app.contacts.get_accounts()):
108
109
110
111
112
113
114
115
116
117
118
119
            if account not in self.disabled_accounts and \
                    not self.is_in_accountstore(account):
                self.account_store.append(row=(account,))

    def update_account_combobox(self):
        if self.plugin_active is False:
            return
        if len(self.account_store) > 0:
            self.B.get_object('account_combobox').set_active(0)
        else:
            self.account_combobox_changed_cb(
                self.B.get_object('account_combobox'))
Philipp Hörist's avatar
Philipp Hörist committed
120
121
122
123

    def account_combobox_changed_cb(self, box, *args):
        self.update_context_list()

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
    def get_qrcode(self, jid, sid, fingerprint):
        file_name = 'omemo_{}.png'.format(jid)
        path = os.path.join(
            configpaths.gajimpaths['MY_DATA'], file_name)

        ver_string = 'xmpp:{}?omemo-sid-{}={}'.format(jid, sid, fingerprint)
        log.debug('Verification String: ' + ver_string)

        if os.path.exists(path):
            return path

        qr = qrcode.QRCode(version=None, error_correction=2, box_size=4, border=1)
        qr.add_data(ver_string)
        qr.make(fit=True)
        img = qr.make_image()
        img.save(path)
        return path

    def update_disabled_account_view(self):
        self.disabled_acc_store.clear()
        for account in self.disabled_accounts:
            self.disabled_acc_store.append(row=(account,))

    def activate_accounts_btn_clicked(self, button, *args):
        mod, paths = self.disabled_acc_view.get_selection().get_selected_rows()
        for path in paths:
            it = mod.get_iter(path)
            account = mod.get(it, 0)
            if account[0] in self.disabled_accounts and \
                    not self.is_in_accountstore(account[0]):
                self.account_store.append(row=(account[0],))
                self.disabled_accounts.remove(account[0])
        self.update_disabled_account_view()
        self.plugin.config['DISABLED_ACCOUNTS'] = self.disabled_accounts
        self.update_account_combobox()

    def disable_accounts_btn_clicked(self, button, *args):
        mod, paths = self.active_acc_view.get_selection().get_selected_rows()
        for path in paths:
            it = mod.get_iter(path)
            account = mod.get(it, 0)
            if account[0] not in self.disabled_accounts and \
                    self.is_in_accountstore(account[0]):
                self.disabled_accounts.append(account[0])
                self.account_store.remove(it)
        self.update_disabled_account_view()
        self.plugin.config['DISABLED_ACCOUNTS'] = self.disabled_accounts
        self.update_account_combobox()

    def delfpr_button_clicked(self, button, *args):
        active = self.B.get_object('account_combobox').get_active()
        account = self.account_store[active][0]

177
        state = self.plugin.get_omemo(account)
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200

        mod, paths = self.fpr_view.get_selection().get_selected_rows()

        def on_yes(checked):
            record = state.store.loadSession(jid, deviceid)
            identity_key = record.getSessionState().getRemoteIdentityKey()

            state.store.deleteSession(jid, deviceid)
            state.store.deleteIdentity(jid, identity_key)
            self.update_context_list()

        for path in paths:
            it = mod.get_iter(path)
            jid, fpr, deviceid = mod.get(it, 1, 3, 4)
            fpr = fpr[31:-12]

            YesNoDialog(
                'Delete Fingerprint?',
                'Do you want to delete the '
                'fingerprint of <b>{}</b> on your account <b>{}</b>?'
                '\n\n<tt>{}</tt>'.format(jid, account, fpr),
                on_response_yes=on_yes, transient_for=self)

Philipp Hörist's avatar
Philipp Hörist committed
201
202
203
204
    def trust_button_clicked_cb(self, button, *args):
        active = self.B.get_object('account_combobox').get_active()
        account = self.account_store[active][0]

205
        state = self.plugin.get_omemo(account)
Philipp Hörist's avatar
Philipp Hörist committed
206
207
208

        mod, paths = self.fpr_view.get_selection().get_selected_rows()

209
        def on_yes(checked, identity_key):
210
            state.store.setTrust(identity_key, State.TRUSTED)
211
212
213
            self.update_context_list()

        def on_no(identity_key):
214
            state.store.setTrust(identity_key, State.UNTRUSTED)
215
216
            self.update_context_list()

Philipp Hörist's avatar
Philipp Hörist committed
217
218
        for path in paths:
            it = mod.get_iter(path)
219
            jid, fpr, deviceid = mod.get(it, 1, 3, 4)
Philipp Hörist's avatar
Philipp Hörist committed
220
221
            fpr = fpr[31:-12]

222
223
224
225
226
227
228
229
230
231
232
            record = state.store.loadSession(jid, deviceid)
            identity_key = record.getSessionState().getRemoteIdentityKey()

            YesNoDialog(
                'Trust / Revoke Fingerprint?',
                'Do you want to trust the fingerprint of <b>{}</b> '
                'on your account <b>{}</b>?\n\n'
                '<tt>{}</tt>'.format(jid, account, fpr),
                on_response_yes=(on_yes, identity_key),
                on_response_no=(on_no, identity_key),
                transient_for=self)
Philipp Hörist's avatar
Philipp Hörist committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256

    def cleardevice_button_clicked_cb(self, button, *args):
        active = self.B.get_object('account_combobox').get_active()
        account = self.account_store[active][0]
        self.plugin.clear_device_list(account)
        self.update_context_list()

    def refresh_button_clicked_cb(self, button, *args):
        self.update_context_list()

    def fpr_button_pressed_cb(self, tw, event):
        if event.button == 3:
            pthinfo = tw.get_path_at_pos(int(event.x), int(event.y))

            if pthinfo is None:
                # only show the popup when we right clicked on list content
                # ie. don't show it when we click at empty rows
                return False

            # if the row under the mouse is already selected, we keep the
            # selection, otherwise we only select the new item
            keep_selection = tw.get_selection().path_is_selected(pthinfo[0])

            pop = self.B.get_object('fprclipboard_menu')
257
            pop.popup(None, None, None, None, event.button, event.time)
Philipp Hörist's avatar
Philipp Hörist committed
258
259
260
261
262
263
264
265
266
267
268
269
270

            # keep_selection=True -> no further processing of click event
            # keep_selection=False-> further processing -> GTK usually selects
            #   the item below the cursor
            return keep_selection

    def clipboard_button_cb(self, menuitem):
        mod, paths = self.fpr_view.get_selection().get_selected_rows()

        fprs = []
        for path in paths:
            it = mod.get_iter(path)
            jid, fpr = mod.get(it, 1, 3)
271
272
273
            fprs.append('%s: %s' % (jid, fpr[31:-12]))
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text('\n'.join(fprs), -1)
Philipp Hörist's avatar
Philipp Hörist committed
274
275
276
277

    def update_context_list(self):
        self.fpr_model.clear()
        self.device_model.clear()
278
279
280
281
282
283
284
285
286
287
288
        self.qrcode = self.B.get_object('qrcode')
        self.qrinfo = self.B.get_object('qrinfo')
        if len(self.account_store) == 0:
            self.B.get_object('ID').set_markup('')
            self.B.get_object('fingerprint_label').set_markup('')
            self.B.get_object('trust_button').set_sensitive(False)
            self.B.get_object('delfprbutton').set_sensitive(False)
            self.B.get_object('refresh').set_sensitive(False)
            self.B.get_object('cleardevice_button').set_sensitive(False)
            self.B.get_object('qrcode').clear()
            return
Philipp Hörist's avatar
Philipp Hörist committed
289
290
291
        active = self.B.get_object('account_combobox').get_active()
        account = self.account_store[active][0]

292
293
294
295
296
297
298
299
300
301
        # Set buttons active
        self.B.get_object('trust_button').set_sensitive(True)
        self.B.get_object('delfprbutton').set_sensitive(True)
        self.B.get_object('refresh').set_sensitive(True)
        if account == 'Local':
            self.B.get_object('cleardevice_button').set_sensitive(False)
        else:
            self.B.get_object('cleardevice_button').set_sensitive(True)

        # Set FPR Label and DeviceID
302
        state = self.plugin.get_omemo(account)
Philipp Hörist's avatar
Philipp Hörist committed
303
304
305
306
307
        deviceid = state.own_device_id
        self.B.get_object('ID').set_markup('<tt>%s</tt>' % deviceid)

        ownfpr = binascii.hexlify(state.store.getIdentityKeyPair()
                                  .getPublicKey().serialize()).decode('utf-8')
308
        human_ownfpr = human_hash(ownfpr[2:])
Philipp Hörist's avatar
Philipp Hörist committed
309
        self.B.get_object('fingerprint_label').set_markup('<tt>%s</tt>'
310
311
312
313
314
315
316
317
318
319
320
321
322
323
                                                          % human_ownfpr)

        # Set Fingerprint List
        trust_str = {0: 'False', 1: 'True', 2: 'Undecided'}
        session_db = state.store.getAllSessions()

        for item in session_db:
            color = {0: '#FF0040',  # red
                     1: '#2EFE2E',  # green
                     2: '#FF8000'}  # orange

            _id, jid, deviceid, record, active = item

            active = bool(active)
Philipp Hörist's avatar
Philipp Hörist committed
324

325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
            identity_key = SessionRecord(serialized=record). \
                getSessionState().getRemoteIdentityKey()
            fpr = binascii.hexlify(
                identity_key.getPublicKey().serialize()).decode('utf-8')
            fpr = human_hash(fpr[2:])

            trust = state.store.isTrustedIdentity(jid, identity_key)

            if not active:
                color[trust] = '#585858'  # grey

            self.fpr_model.append(
                (_id, jid, trust_str[trust],
                 '<tt><span foreground="{}">{}</span></tt>'.
                 format(color[trust], fpr),
                 deviceid))

        # Set Device ID List
Philipp Hörist's avatar
Philipp Hörist committed
343
344
345
        for item in state.own_devices:
            self.device_model.append([item])

346
347
348
        # Set QR Verification Code
        if PILLOW:
            path = self.get_qrcode(
349
                app.get_jid_from_account(account), deviceid, ownfpr[2:])
350
351
352
353
            self.qrcode.set_from_pixbuf(GdkPixbuf.Pixbuf.new_from_file(path))
            self.qrinfo.hide()
        else:
            self.qrinfo.show()
Philipp Hörist's avatar
Philipp Hörist committed
354
355
356


class FingerprintWindow(Gtk.Dialog):
357
358
359
    def __init__(self, plugin, contact, parent, windowinstances,
                 groupchat=False):
        self.groupchat = groupchat
Philipp Hörist's avatar
Philipp Hörist committed
360
361
        self.contact = contact
        self.windowinstances = windowinstances
362
363
        self.account = self.contact.account.name
        self.plugin = plugin
364
        self.con = plugin.connections[self.account]
365
        self.omemostate = self.plugin.get_omemo(self.account)
366
        self.own_jid = app.get_jid_from_account(self.account)
Philipp Hörist's avatar
Philipp Hörist committed
367
368
369
370
371
372
373
        Gtk.Dialog.__init__(self,
                            title=('Fingerprints for %s') % contact.jid,
                            parent=parent,
                            flags=Gtk.DialogFlags.DESTROY_WITH_PARENT)
        close_button = self.add_button(Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)
        close_button.connect('clicked', self.on_close_button_clicked)
        self.connect('delete-event', self.on_window_delete)
374

Philipp Hörist's avatar
Philipp Hörist committed
375
376
        self.GTK_BUILDER_FILE_PATH = \
            self.plugin.local_file_path('fpr_dialog.ui')
377
378
379
        self.xml = Gtk.Builder()
        self.xml.add_from_file(self.GTK_BUILDER_FILE_PATH)
        self.xml.set_translation_domain('gajim_plugins')
Philipp Hörist's avatar
Philipp Hörist committed
380

381
        self.fpr_model = self.xml.get_object('fingerprint_store')
Philipp Hörist's avatar
Philipp Hörist committed
382

383
384
        self.fpr_view = self.xml.get_object('fingerprint_view')
        self.fpr_view_own = self.xml.get_object('fingerprint_view_own')
Philipp Hörist's avatar
Philipp Hörist committed
385

386
        self.notebook = self.xml.get_object('notebook1')
Philipp Hörist's avatar
Philipp Hörist committed
387
388
389
        vbox = self.get_content_area()
        vbox.pack_start(self.notebook, True, True, 0)

390
        self.xml.connect_signals(self)
Philipp Hörist's avatar
Philipp Hörist committed
391

392
        # Set own Fingerprint Label
Philipp Hörist's avatar
Philipp Hörist committed
393
394
        ownfpr = binascii.hexlify(self.omemostate.store.getIdentityKeyPair()
                                  .getPublicKey().serialize()).decode('utf-8')
395
396
397
        ownfpr = human_hash(ownfpr[2:])
        self.xml.get_object('fingerprint_label_own').set_markup('<tt>%s</tt>'
                                                                % ownfpr)
Philipp Hörist's avatar
Philipp Hörist committed
398
399
        self.update_context_list()

400
401
        self.show_all()

Philipp Hörist's avatar
Philipp Hörist committed
402
403
404
405
406
407
408
409
410
    def on_close_button_clicked(self, widget):
        del self.windowinstances['dialog']
        self.hide()

    def on_window_delete(self, widget, event):
        del self.windowinstances['dialog']
        self.hide()

    def trust_button_clicked_cb(self, button, *args):
411
412
        state = self.omemostate

Philipp Hörist's avatar
Philipp Hörist committed
413
414
415
416
417
        if self.notebook.get_current_page() == 1:
            mod, paths = self.fpr_view_own.get_selection().get_selected_rows()
        else:
            mod, paths = self.fpr_view.get_selection().get_selected_rows()

418
        def on_yes(checked, identity_key):
419
            state.store.setTrust(identity_key, State.TRUSTED)
420
421
422
            self.update_context_list()

        def on_no(identity_key):
423
            state.store.setTrust(identity_key, State.UNTRUSTED)
424
425
            self.update_context_list()

Philipp Hörist's avatar
Philipp Hörist committed
426
427
        for path in paths:
            it = mod.get_iter(path)
428
            jid, fpr, deviceid = mod.get(it, 1, 3, 4)
Philipp Hörist's avatar
Philipp Hörist committed
429
430
            fpr = fpr[31:-12]

431
432
433
434
435
436
437
438
439
440
441
            record = state.store.loadSession(jid, deviceid)
            identity_key = record.getSessionState().getRemoteIdentityKey()

            YesNoDialog(
                'Trust / Revoke Fingerprint?',
                'Do you want to trust the fingerprint of <b>{}</b> '
                'on your account <b>{}</b>?\n\n'
                '<tt>{}</tt>'.format(jid, self.account, fpr),
                on_response_yes=(on_yes, identity_key),
                on_response_no=(on_no, identity_key),
                transient_for=self)
Philipp Hörist's avatar
Philipp Hörist committed
442
443
444
445
446
447
448
449
450
451
452
453
454
455

    def fpr_button_pressed_cb(self, tw, event):
        if event.button == 3:
            pthinfo = tw.get_path_at_pos(int(event.x), int(event.y))

            if pthinfo is None:
                # only show the popup when we right clicked on list content
                # ie. don't show it when we click at empty rows
                return False

            # if the row under the mouse is already selected, we keep the
            # selection, otherwise we only select the new item
            keep_selection = tw.get_selection().path_is_selected(pthinfo[0])

456
            pop = self.xml.get_object('fprclipboard_menu')
457
            pop.popup(None, None, None, None, event.button, event.time)
Philipp Hörist's avatar
Philipp Hörist committed
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474

            # keep_selection=True -> no further processing of click event
            # keep_selection=False-> further processing -> GTK usually selects
            #   the item below the cursor
            return keep_selection

    def clipboard_button_cb(self, menuitem):
        if self.notebook.get_current_page() == 1:
            mod, paths = self.fpr_view_own.get_selection().get_selected_rows()
        else:
            mod, paths = self.fpr_view.get_selection().get_selected_rows()

        fprs = []
        for path in paths:
            it = mod.get_iter(path)
            jid, fpr = mod.get(it, 1, 3)
            fprs.append('%s: %s' % (jid, fpr[31:-12]))
475
476
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text('\n'.join(fprs), -1)
Philipp Hörist's avatar
Philipp Hörist committed
477
478
479

    def update_context_list(self, *args):
        self.fpr_model.clear()
480
        state = self.omemostate
Philipp Hörist's avatar
Philipp Hörist committed
481
482

        if self.notebook.get_current_page() == 1:
483
            contact_jid = self.own_jid
Philipp Hörist's avatar
Philipp Hörist committed
484
        else:
485
486
487
488
489
            contact_jid = self.contact.jid

        trust_str = {0: 'False', 1: 'True', 2: 'Undecided'}
        if self.groupchat and self.notebook.get_current_page() == 0:
            contact_jids = []
490
491
            for nick in self.con.groupchat[contact_jid]:
                real_jid = self.con.groupchat[contact_jid][nick]
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
                if real_jid == self.own_jid:
                    continue
                contact_jids.append(real_jid)
            session_db = state.store.getSessionsFromJids(contact_jids)
        else:
            session_db = state.store.getSessionsFromJid(contact_jid)

        for item in session_db:
            color = {0: '#FF0040',  # red
                     1: '#2EFE2E',  # green
                     2: '#FF8000'}  # orange

            _id, jid, deviceid, record, active = item

            active = bool(active)

            identity_key = SessionRecord(serialized=record). \
                getSessionState().getRemoteIdentityKey()
            fpr = binascii.hexlify(identity_key.getPublicKey().serialize()).decode('utf-8')
            fpr = human_hash(fpr[2:])

            trust = state.store.isTrustedIdentity(jid, identity_key)

            if not active:
                color[trust] = '#585858'  # grey

            self.fpr_model.append(
                (_id, jid, trust_str[trust],
                 '<tt><span foreground="{}">{}</span></tt>'.
                 format(color[trust], fpr),
                 deviceid))


def human_hash(fpr):
    fpr = fpr.upper()
    fplen = len(fpr)
    wordsize = fplen // 8
    buf = ''
    for w in range(0, fplen, wordsize):
        buf += '{0} '.format(fpr[w:w + wordsize])
    return buf.rstrip()