handlers.py 55.7 KB
Newer Older
mathieui's avatar
mathieui committed
1
2
3
4
5
6
7
"""
XMPP-related handlers for the Core class
"""

import logging
log = logging.getLogger(__name__)

mathieui's avatar
mathieui committed
8
import asyncio
mathieui's avatar
mathieui committed
9
import curses
mathieui's avatar
mathieui committed
10
import functools
mathieui's avatar
mathieui committed
11
import ssl
mathieui's avatar
mathieui committed
12
import sys
mathieui's avatar
mathieui committed
13
import time
14
from datetime import datetime
15
from hashlib import sha1, sha512
16
from os import path
mathieui's avatar
mathieui committed
17

louiz’'s avatar
louiz’ committed
18
from slixmpp import InvalidJID
19
20
from slixmpp.xmlstream.stanzabase import StanzaBase, ElementBase
from xml.etree import ElementTree as ET
mathieui's avatar
mathieui committed
21

22
23
24
25
26
27
28
29
30
31
32
33
34
35
from poezio import common
from poezio import fixes
from poezio import pep
from poezio import tabs
from poezio import windows
from poezio import xhtml
from poezio import multiuserchat as muc
from poezio.common import safeJID
from poezio.config import config, CACHE_DIR
from poezio.contact import Resource
from poezio.logger import logger
from poezio.roster import roster
from poezio.text_buffer import CorrectionError, AckError
from poezio.theming import dump_tuple, get_theme
mathieui's avatar
mathieui committed
36

mathieui's avatar
mathieui committed
37
from poezio.core.commands import dumb_callback
mathieui's avatar
mathieui committed
38

39
40
41
42
43
44
try:
    from pygments import highlight
    from pygments.lexers import get_lexer_by_name
    from pygments.formatters import HtmlFormatter
    LEXER = get_lexer_by_name('xml')
    FORMATTER = HtmlFormatter(noclasses=True)
45
    PYGMENTS = True
46
except ImportError:
47
    PYGMENTS = False
48

49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
CERT_WARNING_TEXT = """
WARNING: CERTIFICATE FOR %s CHANGED

This can be part of a normal renewal process, but can also mean that \
an attacker is performing a man-in-the-middle attack on your connection.
When in doubt, check with your administrator using another channel.

SHA-512 of the old certificate: %s

SHA-512 of the new certificate: %s
"""

HTTP_VERIF_TEXT = """
Someone (maybe you) has requested an identity verification
using method "%s" for the url "%s".

The transaction id is: %s
And the XMPP address of the verification service is %s.

"""

70
71
72
73
74
75
76
77
78
79
80
81
82

class HandlerCore:
    def __init__(self, core):
        self.core = core

    def on_session_start_features(self, _):
        """
        Enable carbons & blocking on session start if wanted and possible
        """
        def callback(iq):
            if not iq:
                return
            features = iq['disco_info']['features']
83
            rostertab = self.core.get_tab_by_name('Roster', tabs.RosterInfoTab)
84
85
86
87
            rostertab.check_blocking(features)
            rostertab.check_saslexternal(features)
            if (config.get('enable_carbons') and
                    'urn:xmpp:carbons:2' in features):
88
89
                self.core.xmpp.plugin['xep_0280'].enable()
            self.core.check_bookmark_storage(features)
90

91
92
        self.core.xmpp.plugin['xep_0030'].get_info(jid=self.core.xmpp.boundjid.domain,
                                                   callback=callback)
93
94
95
96
97
98
99
100
101

    def on_carbon_received(self, message):
        """
        Carbon <received/> received
        """
        def ignore_message(recv):
            log.debug('%s has category conference, ignoring carbon',
                      recv['from'].server)
        def receive_message(recv):
102
            recv['to'] = self.core.xmpp.boundjid.full
103
104
105
106
107
108
109
            if recv['receipt']:
                return self.on_receipt(recv)
            self.on_normal_message(recv)

        recv = message['carbon_received']
        if (recv['from'].bare not in roster or
            roster[recv['from'].bare].subscription == 'none'):
110
            fixes.has_identity(self.core.xmpp, recv['from'].server,
111
112
113
                               identity='conference',
                               on_true=functools.partial(ignore_message, recv),
                               on_false=functools.partial(receive_message, recv))
mathieui's avatar
mathieui committed
114
            return
115
116
117
118
119
120
121
122
123
124
125
        else:
            receive_message(recv)

    def on_carbon_sent(self, message):
        """
        Carbon <sent/> received
        """
        def ignore_message(sent):
            log.debug('%s has category conference, ignoring carbon',
                      sent['to'].server)
        def send_message(sent):
126
            sent['from'] = self.core.xmpp.boundjid.full
127
128
129
130
131
            self.on_normal_message(sent)

        sent = message['carbon_sent']
        if (sent['to'].bare not in roster or
                roster[sent['to'].bare].subscription == 'none'):
132
            fixes.has_identity(self.core.xmpp, sent['to'].server,
133
134
135
136
137
138
139
140
141
142
143
144
145
                               identity='conference',
                               on_true=functools.partial(ignore_message, sent),
                               on_false=functools.partial(send_message, sent))
        else:
            send_message(sent)

    ### Invites ###

    def on_groupchat_invitation(self, message):
        """
        Mediated invitation received
        """
        jid = message['from']
146
        if jid.bare in self.core.pending_invites:
147
148
            return
        # there are 2 'x' tags in the messages, making message['x'] useless
149
        invite = StanzaBase(self.core.xmpp, xml=message.find('{http://jabber.org/protocol/muc#user}x/{http://jabber.org/protocol/muc#user}invite'))
150
151
152
153
154
155
156
157
        inviter = invite['from']
        reason = invite['reason']
        password = invite['password']
        msg = "You are invited to the room %s by %s" % (jid.full, inviter.full)
        if reason:
            msg += "because: %s" % reason
        if password:
            msg += ". The password is \"%s\"." % password
158
        self.core.information(msg, 'Info')
159
160
161
        if 'invite' in config.get('beep_on').split():
            curses.beep()
        logger.log_roster_change(inviter.full, 'invited you to %s' % jid.full)
162
        self.core.pending_invites[jid.bare] = inviter.full
163
164
165
166
167
168
169
170
171
172

    def on_groupchat_decline(self, decline):
        "Mediated invitation declined; skip for now"
        pass

    def on_groupchat_direct_invitation(self, message):
        """
        Direct invitation received
        """
        room = safeJID(message['groupchat_invite']['jid'])
173
        if room.bare in self.core.pending_invites:
mathieui's avatar
mathieui committed
174
            return
175

176
177
178
179
180
181
182
183
184
185
186
187
188
        inviter = message['from']
        reason = message['groupchat_invite']['reason']
        password = message['groupchat_invite']['password']
        continue_ = message['groupchat_invite']['continue']
        msg = "You are invited to the room %s by %s" % (room, inviter.full)

        if password:
            msg += ' (password: "%s")' % password
        if continue_:
            msg += '\nto continue the discussion'
        if reason:
            msg += "\nreason: %s" % reason

189
        self.core.information(msg, 'Info')
190
191
192
        if 'invite' in config.get('beep_on').split():
            curses.beep()

193
        self.core.pending_invites[room.bare] = inviter.full
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
        logger.log_roster_change(inviter.full, 'invited you to %s' % room.bare)

    ### "classic" messages ###

    def on_message(self, message):
        """
        When receiving private message from a muc OR a normal message
        (from one of our contacts)
        """
        if message.find('{http://jabber.org/protocol/muc#user}x/{http://jabber.org/protocol/muc#user}invite') != None:
            return
        if message['type'] == 'groupchat':
            return
        # Differentiate both type of messages, and call the appropriate handler.
        jid_from = message['from']
209
        for tab in self.core.get_tabs(tabs.MucTab):
210
211
            if tab.name == jid_from.bare:
                if message['type'] == 'chat':
212
213
214
                    self.on_groupchat_private_message(message)
                    return
        self.on_normal_message(message)
215
216
217
218
219
220

    def on_error_message(self, message):
        """
        When receiving any message with type="error"
        """
        jid_from = message['from']
221
        for tab in self.core.get_tabs(tabs.MucTab):
222
            if tab.name == jid_from.bare:
223
                if jid_from.full == jid_from.bare:
224
                    self.core.room_error(message, jid_from.bare)
225
                else:
226
227
228
229
230
231
                    text = self.core.get_error_message(message)
                    p_tab = self.core.get_tab_by_name(jid_from.full, tabs.PrivateTab)
                    if p_tab:
                        p_tab.add_error(text)
                    else:
                        self.core.information(text, 'Error')
232
233
234
                return
        tab = self.core.get_conversation_by_jid(message['from'], create=False)
        error_msg = self.core.get_error_message(message, deprecated=True)
235
        if not tab:
236
237
            self.core.information(error_msg, 'Error')
            return
238
239
240
241
        error = '\x19%s}%s\x19o' % (dump_tuple(get_theme().COLOR_CHAR_NACK),
                                      error_msg)
        if not tab.nack_message('\n' + error, message['id'], message['to']):
            tab.add_message(error, typ=0)
242
            self.core.refresh_window()
243
244
245
246
247
248
249
250
251
252


    def on_normal_message(self, message):
        """
        When receiving "normal" messages (not a private message from a
        muc participant)
        """
        if message['type'] == 'error':
            return
        elif message['type'] == 'headline' and message['body']:
253
            return self.core.information('%s says: %s' % (message['from'], message['body']), 'Headline')
254
255
256
257
258
259
260
261
262

        use_xhtml = config.get('enable_xhtml_im')
        tmp_dir = config.get('tmp_image_dir') or path.join(CACHE_DIR, 'images')
        extract_images = config.get('extract_inline_images')
        body = xhtml.get_body_from_message_stanza(message, use_xhtml=use_xhtml,
                                                  tmp_dir=tmp_dir,
                                                  extract_images=extract_images)
        if not body:
            return
mathieui's avatar
mathieui committed
263

264
265
        remote_nick = ''
        # normal message, we are the recipient
266
        if message['to'].bare == self.core.xmpp.boundjid.bare:
267
268
269
270
271
272
273
274
275
276
            conv_jid = message['from']
            jid = conv_jid
            color = get_theme().COLOR_REMOTE_USER
            # check for a name
            if conv_jid.bare in roster:
                remote_nick = roster[conv_jid.bare].name
            # check for a received nick
            if not remote_nick and config.get('enable_user_nick'):
                if message.xml.find('{http://jabber.org/protocol/nick}nick') is not None:
                    remote_nick = message['nick']['nick']
277
            if not remote_nick:
278
279
280
281
282
                remote_nick = conv_jid.user
                if not remote_nick:
                    remote_nick = conv_jid.full
            own = False
        # we wrote the message (happens with carbons)
283
        elif message['from'].bare == self.core.xmpp.boundjid.bare:
284
            conv_jid = message['to']
285
            jid = self.core.xmpp.boundjid
286
            color = get_theme().COLOR_OWN_NICK
287
            remote_nick = self.core.own_nick
288
289
            own = True
        # we are not part of that message, drop it
mathieui's avatar
mathieui committed
290
        else:
291
292
            return

293
        conversation = self.core.get_conversation_by_jid(conv_jid, create=True)
294
295
296
297
298
        if isinstance(conversation, tabs.DynamicConversationTab) and conv_jid.resource:
            conversation.lock(conv_jid.resource)

        if not own and not conversation.nick:
            conversation.nick = remote_nick
299
300
        elif not own:
            remote_nick = conversation.get_nick()
301

302
        self.core.events.trigger('conversation_msg', message, conversation)
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
        if not message['body']:
            return
        body = xhtml.get_body_from_message_stanza(message, use_xhtml=use_xhtml,
                                                  tmp_dir=tmp_dir,
                                                  extract_images=extract_images)
        delayed, date = common.find_delayed_tag(message)

        def try_modify():
            replaced_id = message['replace']['id']
            if replaced_id and config.get_by_tabname('group_corrections',
                                                     conv_jid.bare):
                try:
                    conversation.modify_message(body, replaced_id, message['id'], jid=jid,
                            nickname=remote_nick)
                    return True
                except CorrectionError:
                    log.debug('Unable to correct a message', exc_info=True)
            return False

        if not try_modify():
            conversation.add_message(body, date,
                    nickname=remote_nick,
                    nick_color=color,
                    history=delayed,
                    identifier=message['id'],
                    jid=jid,
                    typ=1)

        if conversation.remote_wants_chatstates is None and not delayed:
            if message['chat_state']:
                conversation.remote_wants_chatstates = True
            else:
                conversation.remote_wants_chatstates = False
        if not own and 'private' in config.get('beep_on').split():
            if not config.get_by_tabname('disable_beep', conv_jid.bare):
                curses.beep()
339
        if self.core.current_tab() is not conversation:
340
341
            if not own:
                conversation.state = 'private'
342
                self.core.refresh_tab_win()
343
344
            else:
                conversation.set_state('normal')
345
                self.core.refresh_tab_win()
346
        else:
347
            self.core.refresh_window()
mathieui's avatar
mathieui committed
348

349
350
351
352
353
354
355
356
357
358
359
    def on_nick_received(self, message):
        """
        Called when a pep notification for an user nickname
        is received
        """
        contact = roster[message['from'].bare]
        if not contact:
            return
        item = message['pubsub_event']['items']['item']
        if item.xml.find('{http://jabber.org/protocol/nick}nick'):
            contact.name = item['nick']['nick']
mathieui's avatar
mathieui committed
360
        else:
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
            contact.name = ''

    def on_gaming_event(self, message):
        """
        Called when a pep notification for user gaming
        is received
        """
        contact = roster[message['from'].bare]
        if not contact:
            return
        item = message['pubsub_event']['items']['item']
        old_gaming = contact.gaming
        if item.xml.find('{urn:xmpp:gaming:0}gaming'):
            item = item['gaming']
            # only name and server_address are used for now
            contact.gaming = {
                    'character_name': item['character_name'],
                    'character_profile': item['character_profile'],
                    'name': item['name'],
                    'level': item['level'],
                    'uri': item['uri'],
                    'server_name': item['server_name'],
                    'server_address': item['server_address'],
                }
mathieui's avatar
mathieui committed
385
        else:
386
            contact.gaming = {}
mathieui's avatar
mathieui committed
387

388
389
        if contact.gaming:
            logger.log_roster_change(contact.bare_jid, 'is playing %s' % (common.format_gaming_string(contact.gaming)))
mathieui's avatar
mathieui committed
390

391
392
        if old_gaming != contact.gaming and config.get_by_tabname('display_gaming_notifications', contact.bare_jid):
            if contact.gaming:
393
                self.core.information('%s is playing %s' % (contact.bare_jid, common.format_gaming_string(contact.gaming)), 'Gaming')
394
            else:
395
                self.core.information(contact.bare_jid + ' stopped playing.', 'Gaming')
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417

    def on_mood_event(self, message):
        """
        Called when a pep notification for an user mood
        is received.
        """
        contact = roster[message['from'].bare]
        if not contact:
            return
        roster.modified()
        item = message['pubsub_event']['items']['item']
        old_mood = contact.mood
        if item.xml.find('{http://jabber.org/protocol/mood}mood'):
            mood = item['mood']['value']
            if mood:
                mood = pep.MOODS.get(mood, mood)
                text = item['mood']['text']
                if text:
                    mood = '%s (%s)' % (mood, text)
                contact.mood = mood
            else:
                contact.mood = ''
mathieui's avatar
mathieui committed
418
        else:
419
420
421
422
423
424
425
            contact.mood = ''

        if contact.mood:
            logger.log_roster_change(contact.bare_jid, 'has now the mood: %s' % contact.mood)

        if old_mood != contact.mood and config.get_by_tabname('display_mood_notifications', contact.bare_jid):
            if contact.mood:
426
                self.core.information('Mood from '+ contact.bare_jid + ': ' + contact.mood, 'Mood')
427
            else:
428
                self.core.information(contact.bare_jid + ' stopped having his/her mood.', 'Mood')
429
430
431
432
433
434
435
436

    def on_activity_event(self, message):
        """
        Called when a pep notification for an user activity
        is received.
        """
        contact = roster[message['from'].bare]
        if not contact:
mathieui's avatar
mathieui committed
437
            return
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
        roster.modified()
        item = message['pubsub_event']['items']['item']
        old_activity = contact.activity
        if item.xml.find('{http://jabber.org/protocol/activity}activity'):
            try:
                activity = item['activity']['value']
            except ValueError:
                return
            if activity[0]:
                general = pep.ACTIVITIES.get(activity[0])
                s = general['category']
                if activity[1]:
                    s = s + '/' + general.get(activity[1], 'other')
                text = item['activity']['text']
                if text:
                    s = '%s (%s)' % (s, text)
                contact.activity = s
            else:
                contact.activity = ''
mathieui's avatar
mathieui committed
457
458
459
460
        else:
            contact.activity = ''

        if contact.activity:
461
462
463
464
            logger.log_roster_change(contact.bare_jid, 'has now the activity %s' % contact.activity)

        if old_activity != contact.activity and config.get_by_tabname('display_activity_notifications', contact.bare_jid):
            if contact.activity:
465
                self.core.information('Activity from '+ contact.bare_jid + ': ' + contact.activity, 'Activity')
466
            else:
467
                self.core.information(contact.bare_jid + ' stopped doing his/her activity.', 'Activity')
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490

    def on_tune_event(self, message):
        """
        Called when a pep notification for an user tune
        is received
        """
        contact = roster[message['from'].bare]
        if not contact:
            return
        roster.modified()
        item = message['pubsub_event']['items']['item']
        old_tune = contact.tune
        if item.xml.find('{http://jabber.org/protocol/tune}tune'):
            item = item['tune']
            contact.tune = {
                    'artist': item['artist'],
                    'length': item['length'],
                    'rating': item['rating'],
                    'source': item['source'],
                    'title': item['title'],
                    'track': item['track'],
                    'uri': item['uri']
                }
mathieui's avatar
mathieui committed
491
        else:
492
493
            contact.tune = {}

mathieui's avatar
mathieui committed
494
        if contact.tune:
495
            logger.log_roster_change(message['from'].bare, 'is now listening to %s' % common.format_tune_string(contact.tune))
mathieui's avatar
mathieui committed
496

497
498
        if old_tune != contact.tune and config.get_by_tabname('display_tune_notifications', contact.bare_jid):
            if contact.tune:
499
                self.core.information(
500
501
502
                        'Tune from '+ message['from'].bare + ': ' + common.format_tune_string(contact.tune),
                        'Tune')
            else:
503
                self.core.information(contact.bare_jid + ' stopped listening to music.', 'Tune')
mathieui's avatar
mathieui committed
504

505
506
507
508
509
510
511
    def on_groupchat_message(self, message):
        """
        Triggered whenever a message is received from a multi-user chat room.
        """
        if message['subject']:
            return
        room_from = message['from'].bare
mathieui's avatar
mathieui committed
512

513
        if message['type'] == 'error': # Check if it's an error
514
515
            self.core.room_error(message, room_from)
            return
mathieui's avatar
mathieui committed
516

517
        tab = self.core.get_tab_by_name(room_from, tabs.MucTab)
518
        if not tab:
519
520
            self.core.information("message received for a non-existing room: %s" % (room_from))
            muc.leave_groupchat(self.core.xmpp, room_from, self.core.own_nick, msg='')
521
            return
mathieui's avatar
mathieui committed
522

523
524
525
526
        nick_from = message['mucnick']
        user = tab.get_user_by_name(nick_from)
        if user and user in tab.ignores:
            return
mathieui's avatar
mathieui committed
527

528
        self.core.events.trigger('muc_msg', message, tab)
529
530
531
532
533
534
535
536
        use_xhtml = config.get('enable_xhtml_im')
        tmp_dir = config.get('tmp_image_dir') or path.join(CACHE_DIR, 'images')
        extract_images = config.get('extract_inline_images')
        body = xhtml.get_body_from_message_stanza(message, use_xhtml=use_xhtml,
                                                  tmp_dir=tmp_dir,
                                                  extract_images=extract_images)
        if not body:
            return
mathieui's avatar
mathieui committed
537

538
539
540
541
542
543
544
545
546
547
548
        old_state = tab.state
        delayed, date = common.find_delayed_tag(message)
        replaced_id = message['replace']['id']
        replaced = False
        if replaced_id is not '' and config.get_by_tabname('group_corrections',
                                                           message['from'].bare):
            try:
                delayed_date = date or datetime.now()
                if tab.modify_message(body, replaced_id, message['id'],
                        time=delayed_date,
                        nickname=nick_from, user=user):
549
                    self.core.events.trigger('highlight', message, tab)
550
551
552
553
                replaced = True
            except CorrectionError:
                log.debug('Unable to correct a message', exc_info=True)
        if not replaced and tab.add_message(body, date, nick_from, history=delayed, identifier=message['id'], jid=message['from'], typ=1):
554
            self.core.events.trigger('highlight', message, tab)
mathieui's avatar
mathieui committed
555

556
557
558
        if message['from'].resource == tab.own_nick:
            tab.last_sent_message = message

559
        if tab is self.core.current_tab():
560
            tab.text_win.refresh()
561
            tab.info_header.refresh(tab, tab.text_win, user=tab.own_user)
562
            tab.input.refresh()
563
            self.core.doupdate()
564
        elif tab.state != old_state:
565
566
            self.core.refresh_tab_win()
            current = self.core.current_tab()
567
568
            if hasattr(current, 'input') and current.input:
                current.input.refresh()
569
            self.core.doupdate()
570
571
572

        if 'message' in config.get('beep_on').split():
            if (not config.get_by_tabname('disable_beep', room_from)
573
                    and self.core.own_nick != message['from'].resource):
574
575
576
577
                curses.beep()

    def on_muc_own_nickchange(self, muc):
        "We changed our nick in a MUC"
578
        for tab in self.core.get_tabs(tabs.PrivateTab):
579
580
581
582
583
584
585
586
587
588
            if tab.parent_muc == muc:
                tab.own_nick = muc.own_nick

    def on_groupchat_private_message(self, message):
        """
        We received a Private Message (from someone in a Muc)
        """
        jid = message['from']
        nick_from = jid.resource
        if not nick_from:
589
590
            self.on_groupchat_message(message)
            return
591
592
593
594
595
596
597
598

        room_from = jid.bare
        use_xhtml = config.get('enable_xhtml_im')
        tmp_dir = config.get('tmp_image_dir') or path.join(CACHE_DIR, 'images')
        extract_images = config.get('extract_inline_images')
        body = xhtml.get_body_from_message_stanza(message, use_xhtml=use_xhtml,
                                                  tmp_dir=tmp_dir,
                                                  extract_images=extract_images)
599
        tab = self.core.get_tab_by_name(jid.full, tabs.PrivateTab) # get the tab with the private conversation
600
601
602
        ignore = config.get_by_tabname('ignore_private', room_from)
        if not tab: # It's the first message we receive: create the tab
            if body and not ignore:
603
                tab = self.core.open_private_window(room_from, nick_from, False)
604
        if ignore:
605
            self.core.events.trigger('ignored_private', message, tab)
606
607
            msg = config.get_by_tabname('private_auto_response', room_from)
            if msg and body:
608
                self.core.xmpp.send_message(mto=jid.full, mbody=msg, mtype='chat')
609
            return
610
        self.core.events.trigger('private_msg', message, tab)
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
        body = xhtml.get_body_from_message_stanza(message, use_xhtml=use_xhtml,
                                                  tmp_dir=tmp_dir,
                                                  extract_images=extract_images)
        if not body or not tab:
            return
        replaced_id = message['replace']['id']
        replaced = False
        user = tab.parent_muc.get_user_by_name(nick_from)
        if replaced_id is not '' and config.get_by_tabname('group_corrections',
                                                           room_from):
            try:
                tab.modify_message(body, replaced_id, message['id'], user=user, jid=message['from'],
                        nickname=nick_from)
                replaced = True
            except CorrectionError:
                log.debug('Unable to correct a message', exc_info=True)
        if not replaced:
            tab.add_message(body, time=None, nickname=nick_from,
                            forced_user=user,
                            identifier=message['id'],
                            jid=message['from'],
                            typ=1)

        if tab.remote_wants_chatstates is None:
            if message['chat_state']:
                tab.remote_wants_chatstates = True
mathieui's avatar
mathieui committed
637
            else:
638
639
640
641
                tab.remote_wants_chatstates = False
        if 'private' in config.get('beep_on').split():
            if not config.get_by_tabname('disable_beep', jid.full):
                curses.beep()
642
643
        if tab is self.core.current_tab():
            self.core.refresh_window()
644
645
        else:
            tab.state = 'private'
646
            self.core.refresh_tab_win()
mathieui's avatar
mathieui committed
647

648
    ### Chatstates ###
mathieui's avatar
mathieui committed
649

650
    def on_chatstate_active(self, message):
651
        self._on_chatstate(message, "active")
mathieui's avatar
mathieui committed
652

653
    def on_chatstate_inactive(self, message):
654
        self._on_chatstate(message, "inactive")
mathieui's avatar
mathieui committed
655

656
    def on_chatstate_composing(self, message):
657
        self._on_chatstate(message, "composing")
mathieui's avatar
mathieui committed
658

659
    def on_chatstate_paused(self, message):
660
        self._on_chatstate(message, "paused")
mathieui's avatar
mathieui committed
661

662
    def on_chatstate_gone(self, message):
663
        self._on_chatstate(message, "gone")
mathieui's avatar
mathieui committed
664

665
    def _on_chatstate(self, message, state):
666
        if message['type'] == 'chat':
667
668
            if not self._on_chatstate_normal_conversation(message, state):
                tab = self.core.get_tab_by_name(message['from'].full, tabs.PrivateTab)
669
670
                if not tab:
                    return
671
                self._on_chatstate_private_conversation(message, state)
672
673
674
        elif message['type'] == 'groupchat':
            self.on_chatstate_groupchat_conversation(message, state)

675
676
    def _on_chatstate_normal_conversation(self, message, state):
        tab = self.core.get_conversation_by_jid(message['from'], False)
677
678
679
        if not tab:
            return False
        tab.remote_wants_chatstates = True
680
        self.core.events.trigger('normal_chatstate', message, tab)
681
682
        tab.chatstate = state
        if state == 'gone' and isinstance(tab, tabs.DynamicConversationTab):
mathieui's avatar
mathieui committed
683
            tab.unlock()
684
        if tab == self.core.current_tab():
685
            tab.refresh_info_header()
686
            self.core.doupdate()
687
688
        else:
            _composing_tab_state(tab, state)
689
            self.core.refresh_tab_win()
690
        return True
mathieui's avatar
mathieui committed
691

692
    def _on_chatstate_private_conversation(self, message, state):
693
694
695
        """
        Chatstate received in a private conversation from a MUC
        """
696
        tab = self.core.get_tab_by_name(message['from'].full, tabs.PrivateTab)
697
698
699
        if not tab:
            return
        tab.remote_wants_chatstates = True
700
        self.core.events.trigger('private_chatstate', message, tab)
701
        tab.chatstate = state
702
        if tab == self.core.current_tab():
703
            tab.refresh_info_header()
704
            self.core.doupdate()
mathieui's avatar
mathieui committed
705
        else:
706
            _composing_tab_state(tab, state)
707
            self.core.refresh_tab_win()
708
709
710
711
712
713
714

    def on_chatstate_groupchat_conversation(self, message, state):
        """
        Chatstate received in a MUC
        """
        nick = message['mucnick']
        room_from = message.get_mucroom()
715
        tab = self.core.get_tab_by_name(room_from, tabs.MucTab)
716
        if tab and tab.get_user_by_name(nick):
717
            self.core.events.trigger('muc_chatstate', message, tab)
718
            tab.get_user_by_name(nick).chatstate = state
719
720
        if tab == self.core.current_tab():
            if not self.core.size.tab_degrade_x:
721
722
                tab.user_win.refresh(tab.users)
            tab.input.refresh()
723
            self.core.doupdate()
724
725
        else:
            _composing_tab_state(tab, state)
726
            self.core.refresh_tab_win()
mathieui's avatar
mathieui committed
727

728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
    ### subscription-related handlers ###

    def on_roster_update(self, iq):
        """
        The roster was received.
        """
        for item in iq['roster']:
            try:
                jid = item['jid']
            except InvalidJID:
                jid = item._get_attr('jid', '')
                log.error('Invalid JID: "%s"', jid, exc_info=True)
            else:
                if item['subscription'] == 'remove':
                    del roster[jid]
                else:
                    roster.update_contact_groups(jid)
        roster.update_size()
746
747
        if isinstance(self.core.current_tab(), tabs.RosterInfoTab):
            self.core.refresh_window()
mathieui's avatar
mathieui committed
748

749
750
751
752
753
754
755
    def on_subscription_request(self, presence):
        """subscribe received"""
        jid = presence['from'].bare
        contact = roster[jid]
        if contact and contact.subscription in ('from', 'both'):
            return
        elif contact and contact.subscription == 'to':
756
757
            self.core.xmpp.sendPresence(pto=jid, ptype='subscribed')
            self.core.xmpp.sendPresence(pto=jid)
louiz’'s avatar
louiz’ committed
758
        else:
759
760
761
762
            if not contact:
                contact = roster.get_and_set(jid)
            roster.update_contact_groups(contact)
            contact.pending_in = True
763
764
765
766
767
            self.core.information('%s wants to subscribe to your presence, use '
                                  '/accept <jid> or /deny <jid> in the roster '
                                  'tab to accept or reject the query.' % jid,
                                  'Roster')
            self.core.get_tab_by_number(0).state = 'highlight'
768
            roster.modified()
769
770
        if isinstance(self.core.current_tab(), tabs.RosterInfoTab):
            self.core.refresh_window()
mathieui's avatar
mathieui committed
771

772
773
774
775
776
    def on_subscription_authorized(self, presence):
        """subscribed received"""
        jid = presence['from'].bare
        contact = roster[jid]
        if contact.subscription not in ('both', 'from'):
777
            self.core.information('%s accepted your contact proposal' % jid, 'Roster')
778
779
780
781
782
        if contact.pending_out:
            contact.pending_out = False

        roster.modified()

783
784
        if isinstance(self.core.current_tab(), tabs.RosterInfoTab):
            self.core.refresh_window()
785
786
787
788
789
790

    def on_subscription_remove(self, presence):
        """unsubscribe received"""
        jid = presence['from'].bare
        contact = roster[jid]
        if not contact:
mathieui's avatar
mathieui committed
791
            return
792
        roster.modified()
793
794
795
796
        self.core.information('%s does not want to receive your status anymore.' % jid, 'Roster')
        self.core.get_tab_by_number(0).state = 'highlight'
        if isinstance(self.core.current_tab(), tabs.RosterInfoTab):
            self.core.refresh_window()
797
798
799
800
801
802

    def on_subscription_removed(self, presence):
        """unsubscribed received"""
        jid = presence['from'].bare
        contact = roster[jid]
        if not contact:
mathieui's avatar
mathieui committed
803
            return
804
805
        roster.modified()
        if contact.pending_out:
806
            self.core.information('%s rejected your contact proposal' % jid, 'Roster')
807
            contact.pending_out = False
808
        else:
809
810
811
812
            self.core.information('%s does not want you to receive his/her/its status anymore.'%jid, 'Roster')
        self.core.get_tab_by_number(0).state = 'highlight'
        if isinstance(self.core.current_tab(), tabs.RosterInfoTab):
            self.core.refresh_window()
813
814
815
816
817
818
819
820

    ### Presence-related handlers ###

    def on_presence(self, presence):
        if presence.match('presence/muc') or presence.xml.find('{http://jabber.org/protocol/muc#user}x'):
            return
        jid = presence['from']
        contact = roster[jid.bare]
821
        tab = self.core.get_conversation_by_jid(jid, create=False)
822
823
824
825
826
827
828
829
830
        if isinstance(tab, tabs.DynamicConversationTab):
            if tab.get_dest_jid() != jid.full:
                tab.unlock(from_=jid.full)
            elif presence['type'] == 'unavailable':
                tab.unlock()
        if contact is None:
            return
        roster.modified()
        contact.error = None
831
832
833
834
835
        self.core.events.trigger('normal_presence', presence, contact[jid.full])
        tab = self.core.get_conversation_by_jid(jid, create=False)
        if isinstance(self.core.current_tab(), tabs.RosterInfoTab):
            self.core.refresh_window()
        elif self.core.current_tab() == tab:
836
            tab.refresh()
837
            self.core.doupdate()
mathieui's avatar
mathieui committed
838

839
840
841
842
843
844
845
846
    def on_presence_error(self, presence):
        jid = presence['from']
        contact = roster[jid.bare]
        if not contact:
            return
        roster.modified()
        contact.error = presence['error']['type'] + ': ' + presence['error']['condition']
        # reset chat states status on presence error
847
        tab = self.core.get_tab_by_name(jid.full, tabs.ConversationTab)
848
849
850
851
852
853
854
855
856
857
858
        if tab:
            tab.remote_wants_chatstates = None

    def on_got_offline(self, presence):
        """
        A JID got offline
        """
        if presence.match('presence/muc') or presence.xml.find('{http://jabber.org/protocol/muc#user}x'):
            return
        jid = presence['from']
        if not logger.log_roster_change(jid.bare, 'got offline'):
859
            self.core.information('Unable to write in the log file', 'Error')
860
861
862
863
864
865
866
867
868
        # If a resource got offline, display the message in the conversation with this
        # precise resource.
        contact = roster[jid.bare]
        name = jid.bare
        if contact:
            roster.connected -= 1
            if contact.name:
                name = contact.name
        if jid.resource:
869
870
871
            self.core.add_information_message_to_conversation_tab(jid.full, '\x195}%s is \x191}offline' % name)
        self.core.add_information_message_to_conversation_tab(jid.bare, '\x195}%s is \x191}offline' % name)
        self.core.information('\x193}%s \x195}is \x191}offline' % name, 'Roster')
872
        roster.modified()
873
874
        if isinstance(self.core.current_tab(), tabs.RosterInfoTab):
            self.core.refresh_window()
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889

    def on_got_online(self, presence):
        """
        A JID got online
        """
        if presence.match('presence/muc') or presence.xml.find('{http://jabber.org/protocol/muc#user}x'):
            return
        jid = presence['from']
        contact = roster[jid.bare]
        if contact is None:
            # Todo, handle presence coming from contacts not in roster
            return
        roster.connected += 1
        roster.modified()
        if not logger.log_roster_change(jid.bare, 'got online'):
890
            self.core.information('Unable to write in the log file', 'Error')
891
892
893
894
895
        resource = Resource(jid.full, {
            'priority': presence.get_priority() or 0,
            'status': presence['status'],
            'show': presence['show'],
            })
896
        self.core.events.trigger('normal_presence', presence, resource)
897
        name = contact.name if contact.name else jid.bare
898
899
        self.core.add_information_message_to_conversation_tab(jid.full, '\x195}%s is \x194}online' % name)
        if time.time() - self.core.connection_time > 10:
900
901
            # We do not display messages if we recently logged in
            if presence['status']:
902
                self.core.information("\x193}%s \x195}is \x194}online\x195} (\x19o%s\x195})" % (name, presence['status']), "Roster")
903
            else:
904
905
906
907
                self.core.information("\x193}%s \x195}is \x194}online\x195}" % name, "Roster")
            self.core.add_information_message_to_conversation_tab(jid.bare, '\x195}%s is \x194}online' % name)
        if isinstance(self.core.current_tab(), tabs.RosterInfoTab):
            self.core.refresh_window()
908
909
910
911
912
913
914
915

    def on_groupchat_presence(self, presence):
        """
        Triggered whenever a presence stanza is received from a user in a multi-user chat room.
        Display the presence on the room window and update the
        presence information of the concerned user
        """
        from_room = presence['from'].bare
916
        tab = self.core.get_tab_by_name(from_room, tabs.MucTab)
917
        if tab:
918
            self.core.events.trigger('muc_presence', presence, tab)
919
920
921
922
923
924
925
926
927
            tab.handle_presence(presence)


    ### Connection-related handlers ###

    def on_failed_connection(self, error):
        """
        We cannot contact the remote server
        """
928
        self.core.information("Connection to remote server failed: %s" % (error,), 'Error')
929

930
    @asyncio.coroutine
931
932
933
934
935
936
    def on_disconnected(self, event):
        """
        When we are disconnected from remote server
        """
        roster.connected = 0
        # Stop the ping plugin. It would try to send stanza on regular basis
937
        self.core.xmpp.plugin['xep_0199'].disable_keepalive()
938
        roster.modified()
939
        for tab in self.core.get_tabs(tabs.MucTab):
940
            tab.disconnect()
941
942
        msg_typ = 'Error' if not self.core.legitimate_disconnect else 'Info'
        self.core.information("Disconnected from server.", msg_typ)
943
944
945
946
947
948
949
950
        if self.core.legitimate_disconnect or not config.get('auto_reconnect', True):
            return
        if (self.core.last_stream_error and
                self.core.last_stream_error[1]['condition'] in ('conflict', 'host-unknown')):
            return
        yield from asyncio.sleep(1)
        self.core.information("Auto-reconnecting.", 'Info')
        self.core.xmpp.start()
951
952
953
954
955
956

    def on_stream_error(self, event):
        """
        When we receive a stream error
        """
        if event and event['text']:
957
            self.core.information('Stream error: %s' % event['text'], 'Error')
958
959
        if event:
            self.core.last_stream_error = (time.time(), event)
960
961
962
963
964

    def on_failed_all_auth(self, event):
        """
        Authentication failed
        """
965
966
967
        self.core.information("Authentication failed (bad credentials?).",
                              'Error')
        self.core.legitimate_disconnect = True
968
969
970
971
972

    def on_no_auth(self, event):
        """
        Authentication failed (no mech)
        """
973
974
975
        self.core.information("Authentication failed, no login method available.",
                              'Error')
        self.core.legitimate_disconnect = True
976
977
978
979
980

    def on_connected(self, event):
        """
        Remote host responded, but we are not yet authenticated
        """
981
        self.core.information("Connected to server.", 'Info')
982
983
984
985
986

    def on_connecting(self, event):
        """
        Just before we try to connect to the server
        """
987
        self.core.legitimate_disconnect = False
988
989
990
991
992

    def on_session_start(self, event):
        """
        Called when we are connected and authenticated
        """
993
994
995
996
997
998
        self.core.connection_time = time.time()
        if not self.core.plugins_autoloaded: # Do not reload plugins on reconnection
            self.core.autoload_plugins()
        self.core.information("Authentication success.", 'Info')
        self.core.information("Your JID is %s" % self.core.xmpp.boundjid.full, 'Info')
        if not self.core.xmpp.anon:
999
            # request the roster
1000
            self.core.xmpp.get_roster()
For faster browsing, not all history is shown. View entire blame