muctab.py 75.4 KB
Newer Older
1 2 3 4 5 6 7 8 9
"""
Module for the MucTab

A MucTab is a tab for multi-user chats as defined in XEP-0045.

It keeps track of many things such as part/joins, maintains an
user list, and updates private tabs when necessary.
"""

10 11 12
import logging
log = logging.getLogger(__name__)

13
import bisect
14 15 16
import curses
import os
import random
17
import re
mathieui's avatar
mathieui committed
18
from datetime import datetime
19

20
from poezio.tabs import ChatTab, Tab, SHOW_NAME
21

22 23 24 25 26 27 28 29 30 31 32 33 34
from poezio import common
from poezio import fixes
from poezio import multiuserchat as muc
from poezio import timed_events
from poezio import windows
from poezio import xhtml
from poezio.common import safeJID
from poezio.config import config
from poezio.decorators import refresh_wrapper, command_args_parser
from poezio.logger import logger
from poezio.roster import roster
from poezio.theming import get_theme, dump_tuple
from poezio.user import User
35
from poezio.core.structs import Completion, Status
36 37

NS_MUC_USER = 'http://jabber.org/protocol/muc#user'
38
STATUS_XPATH = '{%s}x/{%s}status' % (NS_MUC_USER, NS_MUC_USER)
39 40 41 42 43 44 45 46 47 48


class MucTab(ChatTab):
    """
    The tab containing a multi-user-chat room.
    It contains an userlist, an input, a topic, an information and a chat zone
    """
    message_type = 'groupchat'
    plugin_commands = {}
    plugin_keys = {}
49

50 51
    def __init__(self, core, jid, nick, password=None):
        ChatTab.__init__(self, core, jid)
52 53 54
        self.joined = False
        self._state = 'disconnected'
        # our nick in the MUC
55
        self.own_nick = nick
56
        # self User object
57
        self.own_user = None
58
        self.name = jid
59
        self.password = password
60
        # buffered presences
61
        self.presence_buffer = []
62
        # userlist
63
        self.users = []
64 65
        # private conversations
        self.privates = []
66
        self.topic = ''
67
        self.topic_from = ''
68 69 70
        # Self ping event, so we can cancel it when we leave the room
        self.self_ping_event = None
        # UI stuff
71 72 73 74 75 76 77
        self.topic_win = windows.Topic()
        self.text_win = windows.TextWin()
        self._text_buffer.add_window(self.text_win)
        self.v_separator = windows.VerticalSeparator()
        self.user_win = windows.UserList()
        self.info_header = windows.MucInfoWin()
        self.input = windows.MessageInput()
78 79
        # List of ignored users
        self.ignores = []
80
        # keys
81 82
        self.register_keys()
        self.update_keys()
83
        # commands
84
        self.register_commands()
85
        self.update_commands()
86
        self.resize()
87 88 89

    @property
    def general_jid(self):
90
        return self.name
91

mathieui's avatar
mathieui committed
92 93 94 95
    def check_send_chat_state(self):
        "If we should send a chat state"
        return self.joined

96 97 98 99 100 101 102 103 104 105 106
    @property
    def last_connection(self):
        last_message = self._text_buffer.last_message
        if last_message:
            return last_message.time
        return None

    def cancel_config(self, form):
        """
        The user do not want to send his/her config, send an iq cancel
        """
107
        muc.cancel_config(self.core.xmpp, self.name)
108 109 110 111 112 113
        self.core.close_tab()

    def send_config(self, form):
        """
        The user sends his/her config to the server
        """
114
        muc.configure_room(self.core.xmpp, self.name, form)
115 116
        self.core.close_tab()

117 118 119 120 121 122 123 124 125
    def join(self):
        """
        Join the room
        """
        status = self.core.get_status()
        if self.last_connection:
            delta = datetime.now() - self.last_connection
            seconds = delta.seconds + delta.days * 24 * 3600
        else:
126
            seconds = None
mathieui's avatar
mathieui committed
127 128 129 130 131 132 133 134
        muc.join_groupchat(
            self.core,
            self.name,
            self.own_nick,
            self.password,
            status=status.message,
            show=status.show,
            seconds=seconds)
135

mathieui's avatar
mathieui committed
136 137 138 139 140
    def leave_room(self, message):
        if self.joined:
            info_col = dump_tuple(get_theme().COLOR_INFORMATION_TEXT)
            char_quit = get_theme().CHAR_QUIT
            spec_col = dump_tuple(get_theme().COLOR_QUIT_CHAR)
141

142 143
            if config.get_by_tabname('display_user_color_in_join_part',
                                     self.general_jid):
144 145 146 147
                color = dump_tuple(get_theme().COLOR_OWN_NICK)
            else:
                color = 3

mathieui's avatar
mathieui committed
148
            if message:
149 150
                msg = ('\x19%(color_spec)s}%(spec)s\x19%(info_col)s} '
                       'You (\x19%(color)s}%(nick)s\x19%(info_col)s})'
151
                       ' left the room'
152
                       ' (\x19o%(reason)s\x19%(info_col)s})') % {
mathieui's avatar
mathieui committed
153 154 155 156
                           'info_col': info_col,
                           'reason': message,
                           'spec': char_quit,
                           'color': color,
157 158 159
                           'color_spec': spec_col,
                           'nick': self.own_nick,
                       }
160
            else:
161 162
                msg = ('\x19%(color_spec)s}%(spec)s\x19%(info_col)s} '
                       'You (\x19%(color)s}%(nick)s\x19%(info_col)s})'
163
                       ' left the room') % {
164
                           'info_col': info_col,
mathieui's avatar
mathieui committed
165 166
                           'spec': char_quit,
                           'color': color,
167 168 169
                           'color_spec': spec_col,
                           'nick': self.own_nick,
                       }
170

171
            self.add_message(msg, typ=2)
172
            self.disconnect()
mathieui's avatar
mathieui committed
173 174
            muc.leave_groupchat(self.core.xmpp, self.name, self.own_nick,
                                message)
175
            self.core.disable_private_tabs(self.name, reason=msg)
176
        else:
mathieui's avatar
mathieui committed
177 178
            muc.leave_groupchat(self.core.xmpp, self.name, self.own_nick,
                                message)
mathieui's avatar
mathieui committed
179

180 181 182 183
    def change_affiliation(self, nick_or_jid, affiliation, reason=''):
        """
        Change the affiliation of a nick or JID
        """
mathieui's avatar
mathieui committed
184

185 186
        def callback(iq):
            if iq['type'] == 'error':
mathieui's avatar
mathieui committed
187 188 189 190
                self.core.information(
                    "Could not set affiliation '%s' for '%s'." %
                    (affiliation, nick_or_jid), "Warning")

191 192 193 194 195
        if not self.joined:
            return

        valid_affiliations = ('outcast', 'none', 'member', 'admin', 'owner')
        if affiliation not in valid_affiliations:
mathieui's avatar
mathieui committed
196 197 198
            return self.core.information(
                'The affiliation must be one of ' +
                ', '.join(valid_affiliations), 'Error')
199
        if nick_or_jid in [user.nick for user in self.users]:
mathieui's avatar
mathieui committed
200
            muc.set_user_affiliation(
mathieui's avatar
mathieui committed
201 202 203 204 205 206
                self.core.xmpp,
                self.name,
                affiliation,
                nick=nick_or_jid,
                callback=callback,
                reason=reason)
207
        else:
mathieui's avatar
mathieui committed
208
            muc.set_user_affiliation(
mathieui's avatar
mathieui committed
209 210 211 212 213 214
                self.core.xmpp,
                self.name,
                affiliation,
                jid=safeJID(nick_or_jid),
                callback=callback,
                reason=reason)
215 216 217 218 219

    def change_role(self, nick, role, reason=''):
        """
        Change the role of a nick
        """
mathieui's avatar
mathieui committed
220

221 222
        def callback(iq):
            if iq['type'] == 'error':
mathieui's avatar
mathieui committed
223 224 225
                self.core.information(
                    "Could not set role '%s' for '%s'." % (role, nick),
                    "Warning")
mathieui's avatar
mathieui committed
226

227 228 229
        valid_roles = ('none', 'visitor', 'participant', 'moderator')

        if not self.joined or role not in valid_roles:
mathieui's avatar
mathieui committed
230 231
            return self.core.information(
                'The role must be one of ' + ', '.join(valid_roles), 'Error')
232 233 234

        if not safeJID(self.name + '/' + nick):
            return self.core.information('Invalid nick', 'Info')
mathieui's avatar
mathieui committed
235 236
        muc.set_user_role(
            self.core.xmpp, self.name, nick, reason, role, callback=callback)
237

mathieui's avatar
mathieui committed
238 239 240 241 242 243 244 245 246 247 248
    @refresh_wrapper.conditional
    def print_info(self, nick):
        """Print information about a user"""
        user = self.get_user_by_name(nick)
        if not user:
            return False

        theme = get_theme()
        inf = '\x19' + dump_tuple(theme.COLOR_INFORMATION_TEXT) + '}'
        if user.jid:
            user_jid = '%s (\x19%s}%s\x19o%s)' % (
mathieui's avatar
mathieui committed
249
                inf, dump_tuple(theme.COLOR_MUC_JID), user.jid, inf)
mathieui's avatar
mathieui committed
250 251 252 253 254 255
        else:
            user_jid = ''
        info = ('\x19%(user_col)s}%(nick)s\x19o%(jid)s%(info)s: show: '
                '\x19%(show_col)s}%(show)s\x19o%(info)s, affiliation: '
                '\x19%(role_col)s}%(affiliation)s\x19o%(info)s, role: '
                '\x19%(role_col)s}%(role)s\x19o%(status)s') % {
mathieui's avatar
mathieui committed
256 257 258 259 260 261 262 263 264 265 266
                    'user_col': dump_tuple(user.color),
                    'nick': nick,
                    'jid': user_jid,
                    'info': inf,
                    'show_col': dump_tuple(theme.color_show(user.show)),
                    'show': user.show or 'Available',
                    'role_col': dump_tuple(theme.color_role(user.role)),
                    'affiliation': user.affiliation or 'None',
                    'role': user.role or 'None',
                    'status': '\n%s' % user.status if user.status else ''
                }
mathieui's avatar
mathieui committed
267 268 269
        self.add_message(info, typ=0)
        return True

mathieui's avatar
mathieui committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    def change_topic(self, topic):
        """Change the current topic"""
        muc.change_subject(self.core.xmpp, self.name, topic)

    @refresh_wrapper.always
    def show_topic(self):
        """
        Print the current topic
        """
        info_text = dump_tuple(get_theme().COLOR_INFORMATION_TEXT)
        norm_text = dump_tuple(get_theme().COLOR_NORMAL_TEXT)
        if self.topic_from:
            user = self.get_user_by_name(self.topic_from)
            if user:
                user_text = dump_tuple(user.color)
mathieui's avatar
mathieui committed
285 286
                user_string = '\x19%s}(set by \x19%s}%s\x19%s})' % (
                    info_text, user_text, user.nick, info_text)
mathieui's avatar
mathieui committed
287 288 289 290 291 292
            else:
                user_string = self.topic_from
        else:
            user_string = ''

        self._text_buffer.add_message(
mathieui's avatar
mathieui committed
293 294
            "\x19%s}The subject of the room is: \x19%s}%s %s" %
            (info_text, norm_text, self.topic, user_string))
mathieui's avatar
mathieui committed
295

mathieui's avatar
mathieui committed
296 297 298
    @refresh_wrapper.always
    def recolor(self, random_colors=False):
        """Recolor the current MUC users"""
mathieui's avatar
mathieui committed
299 300
        deterministic = config.get_by_tabname('deterministic_nick_colors',
                                              self.name)
mathieui's avatar
mathieui committed
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
        if deterministic:
            for user in self.users:
                if user is self.own_user:
                    continue
                color = self.search_for_color(user.nick)
                if color != '':
                    continue
                user.set_deterministic_color()
            return
        # Sort the user list by last talked, to avoid color conflicts
        # on active participants
        compare_users = lambda x: x.last_talked
        sorted_users = sorted(self.users, key=compare_users, reverse=True)
        full_sorted_users = sorted_users[:]
        # search our own user, to remove it from the list
        # Also remove users whose color is fixed
        for user in full_sorted_users:
            color = self.search_for_color(user.nick)
            if user is self.own_user:
                sorted_users.remove(user)
            elif color != '':
                sorted_users.remove(user)
                user.change_color(color, deterministic)
        colors = list(get_theme().LIST_COLOR_NICKNAMES)
        if random_colors:
            random.shuffle(colors)
        for i, user in enumerate(sorted_users):
            user.color = colors[i % len(colors)]
        self.text_win.rebuild_everything(self._text_buffer)

331 332 333 334 335 336 337 338 339 340
    @refresh_wrapper.conditional
    def set_nick_color(self, nick, color):
        "Set a custom color for a nick, permanently"
        user = self.get_user_by_name(nick)
        if color not in xhtml.colors and color not in ('unset', 'random'):
            return False
        if nick == self.own_nick:
            return False
        if color == 'unset':
            if config.remove_and_save(nick, 'muc_colors'):
mathieui's avatar
mathieui committed
341 342
                self.core.information('Color for nick %s unset' % (nick),
                                      'Info')
343 344 345 346 347 348
        else:
            if color == 'random':
                color = random.choice(list(xhtml.colors))
            if user:
                user.change_color(color)
            config.set_and_save(nick, color, 'muc_colors')
mathieui's avatar
mathieui committed
349 350
            nick_color_aliases = config.get_by_tabname('nick_color_aliases',
                                                       self.name)
351 352 353 354 355 356 357 358 359 360 361
            if nick_color_aliases:
                # if any user in the room has a nick which is an alias of the
                # nick, update its color
                for tab in self.core.get_tabs(MucTab):
                    for u in tab.users:
                        nick_alias = re.sub('^_*', '', u.nick)
                        nick_alias = re.sub('_*$', '', nick_alias)
                        if nick_alias == nick:
                            u.change_color(color)
        self.text_win.rebuild_everything(self._text_buffer)
        return True
mathieui's avatar
mathieui committed
362

mathieui's avatar
mathieui committed
363 364 365 366 367 368
    def on_input(self, key, raw):
        if not raw and key in self.key_func:
            self.key_func[key]()
            return False
        self.input.do_command(key, raw=raw)
        empty_after = self.input.get_text() == ''
mathieui's avatar
mathieui committed
369 370 371
        empty_after = empty_after or (
            self.input.get_text().startswith('/')
            and not self.input.get_text().startswith('//'))
mathieui's avatar
mathieui committed
372 373
        self.send_composing_chat_state(empty_after)
        return False
374

mathieui's avatar
mathieui committed
375
    def get_nick(self):
376 377 378 379 380 381 382
        if config.get('show_muc_jid'):
            return self.name
        bookmark = self.core.bookmarks[self.name]
        if bookmark is not None and bookmark.name:
            return bookmark.name
        # TODO: send the disco#info identity name here, if it exists.
        return safeJID(self.name).user
383

mathieui's avatar
mathieui committed
384 385
    def get_text_window(self):
        return self.text_win
386

mathieui's avatar
mathieui committed
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
    def on_lose_focus(self):
        if self.joined:
            if self.input.text:
                self.state = 'nonempty'
            else:
                self.state = 'normal'
        else:
            self.state = 'disconnected'
        self.text_win.remove_line_separator()
        self.text_win.add_line_separator(self._text_buffer)
        if config.get_by_tabname('send_chat_states', self.general_jid):
            self.send_chat_state('inactive')
        self.check_scrolled()

    def on_gain_focus(self):
        self.state = 'current'
        if (self.text_win.built_lines and self.text_win.built_lines[-1] is None
                and not config.get('show_useless_separator')):
            self.text_win.remove_line_separator()
        curses.curs_set(1)
mathieui's avatar
mathieui committed
407 408
        if self.joined and config.get_by_tabname(
                'send_chat_states',
mathieui's avatar
mathieui committed
409 410 411 412
                self.general_jid) and not self.input.get_text():
            self.send_chat_state('active')

    def handle_presence(self, presence):
413
        """
mathieui's avatar
mathieui committed
414
        Handle MUC presence
415
        """
mathieui's avatar
mathieui committed
416 417 418
        status_codes = set()
        for status_code in presence.xml.findall(STATUS_XPATH):
            status_codes.add(status_code.attrib['code'])
mathieui's avatar
mathieui committed
419 420 421
        if presence['type'] == 'error':
            self.core.room_error(presence, self.name)
        elif not self.joined:
mathieui's avatar
mathieui committed
422
            if '110' in status_codes:
mathieui's avatar
mathieui committed
423
                self.process_presence_buffer(presence)
mathieui's avatar
mathieui committed
424 425 426 427 428 429 430 431
            else:
                self.presence_buffer.append(presence)
                return
        else:
            try:
                self.handle_presence_joined(presence, status_codes)
            except PresenceError:
                self.core.room_error(presence, presence['from'].bare)
432
        if self.core.tabs.current_tab is self:
mathieui's avatar
mathieui committed
433 434 435 436 437
            self.text_win.refresh()
            self.user_win.refresh_if_changed(self.users)
            self.info_header.refresh(self, self.text_win, user=self.own_user)
            self.input.refresh()
            self.core.doupdate()
438

mathieui's avatar
mathieui committed
439
    def process_presence_buffer(self, last_presence):
440
        """
mathieui's avatar
mathieui committed
441
        Batch-process all the initial presences
442
        """
mathieui's avatar
mathieui committed
443 444
        deterministic = config.get_by_tabname('deterministic_nick_colors',
                                              self.name)
mathieui's avatar
mathieui committed
445

mathieui's avatar
mathieui committed
446 447 448 449 450 451 452 453 454 455
        for stanza in self.presence_buffer:
            try:
                self.handle_presence_unjoined(stanza, deterministic)
            except PresenceError:
                self.core.room_error(stanza, stanza['from'].bare)
        self.handle_presence_unjoined(last_presence, deterministic, own=True)
        self.users.sort()
        # Enable the self ping event, to regularly check if we
        # are still in the room.
        self.enable_self_ping_event()
456
        if self.core.tabs.current_tab is not self:
mathieui's avatar
mathieui committed
457
            self.refresh_tab_win()
458
            self.core.tabs.current_tab.refresh_input()
mathieui's avatar
mathieui committed
459
            self.core.doupdate()
460

mathieui's avatar
mathieui committed
461 462 463 464
    def handle_presence_unjoined(self, presence, deterministic, own=False):
        """
        Presence received while we are not in the room (before code=110)
        """
mathieui's avatar
mathieui committed
465
        from_nick, _, affiliation, show, status, role, jid, typ = dissect_presence(
mathieui's avatar
mathieui committed
466
            presence)
467 468
        if typ == 'unavailable':
            return
mathieui's avatar
mathieui committed
469
        user_color = self.search_for_color(from_nick)
mathieui's avatar
mathieui committed
470 471
        new_user = User(from_nick, affiliation, show, status, role, jid,
                        deterministic, user_color)
mathieui's avatar
mathieui committed
472 473 474 475 476 477 478
        self.users.append(new_user)
        self.core.events.trigger('muc_join', presence, self)
        if own:
            status_codes = set()
            for status_code in presence.xml.findall(STATUS_XPATH):
                status_codes.add(status_code.attrib['code'])
            self.own_join(from_nick, new_user, status_codes)
479

mathieui's avatar
mathieui committed
480
    def own_join(self, from_nick, new_user, status_codes):
481
        """
mathieui's avatar
mathieui committed
482
        Handle the last presence we received, entering the room
483
        """
mathieui's avatar
mathieui committed
484 485 486 487 488 489
        self.own_nick = from_nick
        self.own_user = new_user
        self.joined = True
        if self.name in self.core.initial_joins:
            self.core.initial_joins.remove(self.name)
            self._state = 'normal'
490
        elif self != self.core.tabs.current_tab:
mathieui's avatar
mathieui committed
491
            self._state = 'joined'
492
        if (self.core.tabs.current_tab is self
mathieui's avatar
mathieui committed
493 494 495
                and self.core.status.show not in ('xa', 'away')):
            self.send_chat_state('active')
        new_user.color = get_theme().COLOR_OWN_NICK
496

mathieui's avatar
mathieui committed
497 498 499 500 501
        if config.get_by_tabname('display_user_color_in_join_part',
                                 self.general_jid):
            color = dump_tuple(new_user.color)
        else:
            color = 3
502

mathieui's avatar
mathieui committed
503 504 505
        info_col = dump_tuple(get_theme().COLOR_INFORMATION_TEXT)
        warn_col = dump_tuple(get_theme().COLOR_WARNING_TEXT)
        spec_col = dump_tuple(get_theme().COLOR_JOIN_CHAR)
mathieui's avatar
mathieui committed
506 507 508 509 510 511 512 513 514
        enable_message = ('\x19%(color_spec)s}%(spec)s\x19%(info_col)s} You '
                          '(\x19%(nick_col)s}%(nick)s\x19%(info_col)s}) joined'
                          ' the room') % {
                              'nick': from_nick,
                              'spec': get_theme().CHAR_JOIN,
                              'color_spec': spec_col,
                              'nick_col': color,
                              'info_col': info_col,
                          }
mathieui's avatar
mathieui committed
515 516 517 518
        self.add_message(enable_message, typ=2)
        self.core.enable_private_tabs(self.name, enable_message)
        if '201' in status_codes:
            self.add_message(
mathieui's avatar
mathieui committed
519 520
                '\x19%(info_col)s}Info: The room '
                'has been created' % {'info_col': info_col},
mathieui's avatar
mathieui committed
521 522 523
                typ=0)
        if '170' in status_codes:
            self.add_message(
mathieui's avatar
mathieui committed
524
                '\x19%(warn_col)s}Warning:\x19%(info_col)s}'
mathieui's avatar
mathieui committed
525 526 527 528
                ' This room is publicly logged' % {
                    'info_col': info_col,
                    'warn_col': warn_col
                },
mathieui's avatar
mathieui committed
529 530 531
                typ=0)
        if '100' in status_codes:
            self.add_message(
mathieui's avatar
mathieui committed
532
                '\x19%(warn_col)s}Warning:\x19%(info_col)s}'
mathieui's avatar
mathieui committed
533 534 535 536
                ' This room is not anonymous.' % {
                    'info_col': info_col,
                    'warn_col': warn_col
                },
mathieui's avatar
mathieui committed
537
                typ=0)
538

mathieui's avatar
mathieui committed
539
    def handle_presence_joined(self, presence, status_codes):
540
        """
mathieui's avatar
mathieui committed
541
        Handle new presences when we are already in the room
542
        """
mathieui's avatar
mathieui committed
543 544
        from_nick, from_room, affiliation, show, status, role, jid, typ = dissect_presence(
            presence)
mathieui's avatar
mathieui committed
545 546 547 548 549 550 551 552 553 554
        change_nick = '303' in status_codes
        kick = '307' in status_codes and typ == 'unavailable'
        ban = '301' in status_codes and typ == 'unavailable'
        shutdown = '332' in status_codes and typ == 'unavailable'
        non_member = '322' in status_codes and typ == 'unavailable'
        user = self.get_user_by_name(from_nick)
        # New user
        if not user and typ != "unavailable":
            user_color = self.search_for_color(from_nick)
            self.core.events.trigger('muc_join', presence, self)
mathieui's avatar
mathieui committed
555 556
            self.on_user_join(from_nick, affiliation, show, status, role, jid,
                              user_color)
mathieui's avatar
mathieui committed
557 558 559 560 561 562 563 564
        elif user is None:
            log.error('BUG: User %s in %s is None', from_nick, self.name)
            return
        elif change_nick:
            self.core.events.trigger('muc_nickchange', presence, self)
            self.on_user_nick_change(presence, user, from_nick, from_room)
        elif ban:
            self.core.events.trigger('muc_ban', presence, self)
mathieui's avatar
mathieui committed
565 566
            self.core.on_user_left_private_conversation(
                from_room, user, status)
mathieui's avatar
mathieui committed
567 568 569
            self.on_user_banned(presence, user, from_nick)
        elif kick:
            self.core.events.trigger('muc_kick', presence, self)
mathieui's avatar
mathieui committed
570 571
            self.core.on_user_left_private_conversation(
                from_room, user, status)
mathieui's avatar
mathieui committed
572 573 574 575 576 577 578 579 580
            self.on_user_kicked(presence, user, from_nick)
        elif shutdown:
            self.core.events.trigger('muc_shutdown', presence, self)
            self.on_muc_shutdown()
        elif non_member:
            self.core.events.trigger('muc_shutdown', presence, self)
            self.on_non_member_kicked()
        # user quit
        elif typ == 'unavailable':
mathieui's avatar
mathieui committed
581 582
            self.on_user_leave_groupchat(user, jid, status, from_nick,
                                         from_room)
mathieui's avatar
mathieui committed
583
        # status change
584
        else:
mathieui's avatar
mathieui committed
585 586
            self.on_user_change_status(user, from_nick, from_room, affiliation,
                                       role, show, status)
587

mathieui's avatar
mathieui committed
588 589 590
    def on_non_member_kicked(self):
        """We have been kicked because the MUC is members-only"""
        self.add_message(
mathieui's avatar
mathieui committed
591 592 593
            '\x19%(info_col)s}You have been kicked because you '
            'are not a member and the room is now members-only.' %
            {'info_col': dump_tuple(get_theme().COLOR_INFORMATION_TEXT)},
mathieui's avatar
mathieui committed
594 595 596 597 598 599
            typ=2)
        self.disconnect()

    def on_muc_shutdown(self):
        """We have been kicked because the MUC service is shutting down"""
        self.add_message(
mathieui's avatar
mathieui committed
600 601 602
            '\x19%(info_col)s}You have been kicked because the'
            ' MUC service is shutting down.' %
            {'info_col': dump_tuple(get_theme().COLOR_INFORMATION_TEXT)},
mathieui's avatar
mathieui committed
603 604 605
            typ=2)
        self.disconnect()

mathieui's avatar
mathieui committed
606 607
    def on_user_join(self, from_nick, affiliation, show, status, role, jid,
                     color):
608
        """
mathieui's avatar
mathieui committed
609
        When a new user joins the groupchat
610
        """
mathieui's avatar
mathieui committed
611 612 613 614
        deterministic = config.get_by_tabname('deterministic_nick_colors',
                                              self.name)
        user = User(from_nick, affiliation, show, status, role, jid,
                    deterministic, color)
mathieui's avatar
mathieui committed
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
        bisect.insort_left(self.users, user)
        hide_exit_join = config.get_by_tabname('hide_exit_join',
                                               self.general_jid)
        if hide_exit_join != 0:
            if config.get_by_tabname('display_user_color_in_join_part',
                                     self.general_jid):
                color = dump_tuple(user.color)
            else:
                color = 3
            info_col = dump_tuple(get_theme().COLOR_INFORMATION_TEXT)
            spec_col = dump_tuple(get_theme().COLOR_JOIN_CHAR)
            char_join = get_theme().CHAR_JOIN
            if not jid.full:
                msg = ('\x19%(color_spec)s}%(spec)s \x19%(color)s}%(nick)s'
                       '\x19%(info_col)s} joined the room') % {
mathieui's avatar
mathieui committed
630 631 632 633 634 635
                           'nick': from_nick,
                           'spec': char_join,
                           'color': color,
                           'info_col': info_col,
                           'color_spec': spec_col,
                       }
mathieui's avatar
mathieui committed
636 637 638 639
            else:
                msg = ('\x19%(color_spec)s}%(spec)s \x19%(color)s}%(nick)s'
                       '\x19%(info_col)s} (\x19%(jid_color)s}%(jid)s\x19'
                       '%(info_col)s}) joined the room') % {
mathieui's avatar
mathieui committed
640 641 642 643 644 645 646 647
                           'spec': char_join,
                           'nick': from_nick,
                           'color': color,
                           'jid': jid.full,
                           'info_col': info_col,
                           'jid_color': dump_tuple(get_theme().COLOR_MUC_JID),
                           'color_spec': spec_col,
                       }
mathieui's avatar
mathieui committed
648 649 650 651
            self.add_message(msg, typ=2)
        self.core.on_user_rejoined_private_conversation(self.name, from_nick)

    def on_user_nick_change(self, presence, user, from_nick, from_room):
mathieui's avatar
mathieui committed
652 653
        new_nick = presence.xml.find(
            '{%s}x/{%s}item' % (NS_MUC_USER, NS_MUC_USER)).attrib['nick']
654
        old_color = user.color
mathieui's avatar
mathieui committed
655 656 657 658
        if user.nick == self.own_nick:
            self.own_nick = new_nick
            # also change our nick in all private discussions of this room
            self.core.handler.on_muc_own_nickchange(self)
659
            user.change_nick(new_nick)
660
        else:
661
            user.change_nick(new_nick)
mathieui's avatar
mathieui committed
662 663
            deterministic = config.get_by_tabname('deterministic_nick_colors',
                                                  self.name)
664 665
            color = config.get_by_tabname(new_nick, 'muc_colors') or None
            if color or deterministic:
mathieui's avatar
mathieui committed
666 667 668
                user.change_color(color, deterministic)
        self.users.remove(user)
        bisect.insort_left(self.users, user)
669

mathieui's avatar
mathieui committed
670 671 672
        if config.get_by_tabname('display_user_color_in_join_part',
                                 self.general_jid):
            color = dump_tuple(user.color)
673
            old_color = dump_tuple(old_color)
674
        else:
675
            old_color = color = 3
mathieui's avatar
mathieui committed
676
        info_col = dump_tuple(get_theme().COLOR_INFORMATION_TEXT)
mathieui's avatar
mathieui committed
677
        self.add_message(
678
            '\x19%(old_color)s}%(old)s\x19%(info_col)s} is'
mathieui's avatar
mathieui committed
679 680 681 682
            ' now known as \x19%(color)s}%(new)s' % {
                'old': from_nick,
                'new': new_nick,
                'color': color,
683
                'old_color': old_color,
mathieui's avatar
mathieui committed
684 685 686
                'info_col': info_col
            },
            typ=2)
mathieui's avatar
mathieui committed
687 688
        # rename the private tabs if needed
        self.core.rename_private_tabs(self.name, from_nick, user)
689

mathieui's avatar
mathieui committed
690
    def on_user_banned(self, presence, user, from_nick):
691
        """
mathieui's avatar
mathieui committed
692
        When someone is banned from a muc
693
        """
mathieui's avatar
mathieui committed
694 695 696 697 698 699 700 701 702
        self.users.remove(user)
        by = presence.xml.find('{%s}x/{%s}item/{%s}actor' %
                               (NS_MUC_USER, NS_MUC_USER, NS_MUC_USER))
        reason = presence.xml.find('{%s}x/{%s}item/{%s}reason' %
                                   (NS_MUC_USER, NS_MUC_USER, NS_MUC_USER))
        if by:
            by = by.get('jid') or by.get('nick') or None
        else:
            by = None
703

mathieui's avatar
mathieui committed
704 705
        info_col = dump_tuple(get_theme().COLOR_INFORMATION_TEXT)
        char_kick = get_theme().CHAR_KICK
706

mathieui's avatar
mathieui committed
707
        if from_nick == self.own_nick:  # we are banned
mathieui's avatar
mathieui committed
708 709 710
            if by:
                kick_msg = ('\x191}%(spec)s \x193}You\x19%(info_col)s}'
                            ' have been banned by \x194}%(by)s') % {
mathieui's avatar
mathieui committed
711 712 713 714
                                'spec': char_kick,
                                'by': by,
                                'info_col': info_col
                            }
mathieui's avatar
mathieui committed
715 716 717
            else:
                kick_msg = ('\x191}%(spec)s \x193}You\x19'
                            '%(info_col)s} have been banned.') % {
mathieui's avatar
mathieui committed
718 719 720
                                'spec': char_kick,
                                'info_col': info_col
                            }
mathieui's avatar
mathieui committed
721 722 723
            self.core.disable_private_tabs(self.name, reason=kick_msg)
            self.disconnect()
            self.refresh_tab_win()
724
            self.core.tabs.current_tab.refresh_input()
mathieui's avatar
mathieui committed
725 726 727 728 729 730 731
            if config.get_by_tabname('autorejoin', self.general_jid):
                delay = config.get_by_tabname('autorejoin_delay',
                                              self.general_jid)
                delay = common.parse_str_to_secs(delay)
                if delay <= 0:
                    muc.join_groupchat(self.core, self.name, self.own_nick)
                else:
mathieui's avatar
mathieui committed
732 733 734
                    self.core.add_timed_event(
                        timed_events.DelayedEvent(delay, muc.join_groupchat,
                                                  self.core, self.name,
mathieui's avatar
mathieui committed
735
                                                  self.own_nick))
736

mathieui's avatar
mathieui committed
737 738 739 740 741 742 743 744 745 746 747
        else:
            if config.get_by_tabname('display_user_color_in_join_part',
                                     self.general_jid):
                color = dump_tuple(user.color)
            else:
                color = 3

            if by:
                kick_msg = ('\x191}%(spec)s \x19%(color)s}'
                            '%(nick)s\x19%(info_col)s} '
                            'has been banned by \x194}%(by)s') % {
mathieui's avatar
mathieui committed
748 749 750 751 752 753
                                'spec': char_kick,
                                'nick': from_nick,
                                'color': color,
                                'by': by,
                                'info_col': info_col
                            }
mathieui's avatar
mathieui committed
754 755 756
            else:
                kick_msg = ('\x191}%(spec)s \x19%(color)s}%(nick)s'
                            '\x19%(info_col)s} has been banned') % {
mathieui's avatar
mathieui committed
757 758 759 760 761
                                'spec': char_kick,
                                'nick': from_nick,
                                'color': color,
                                'info_col': info_col
                            }
mathieui's avatar
mathieui committed
762 763 764
        if reason is not None and reason.text:
            kick_msg += ('\x19%(info_col)s} Reason: \x196}'
                         '%(reason)s\x19%(info_col)s}') % {
mathieui's avatar
mathieui committed
765 766 767
                             'reason': reason.text,
                             'info_col': info_col
                         }
mathieui's avatar
mathieui committed
768 769 770
        self.add_message(kick_msg, typ=2)

    def on_user_kicked(self, presence, user, from_nick):
771
        """
mathieui's avatar
mathieui committed
772
        When someone is kicked from a muc
773
        """
mathieui's avatar
mathieui committed
774 775 776 777 778 779 780 781 782 783
        self.users.remove(user)
        actor_elem = presence.xml.find('{%s}x/{%s}item/{%s}actor' %
                                       (NS_MUC_USER, NS_MUC_USER, NS_MUC_USER))
        reason = presence.xml.find('{%s}x/{%s}item/{%s}reason' %
                                   (NS_MUC_USER, NS_MUC_USER, NS_MUC_USER))
        by = None
        info_col = dump_tuple(get_theme().COLOR_INFORMATION_TEXT)
        char_kick = get_theme().CHAR_KICK
        if actor_elem is not None:
            by = actor_elem.get('nick') or actor_elem.get('jid')
mathieui's avatar
mathieui committed
784
        if from_nick == self.own_nick:  # we are kicked
mathieui's avatar
mathieui committed
785 786 787 788
            if by:
                kick_msg = ('\x191}%(spec)s \x193}You\x19'
                            '%(info_col)s} have been kicked'
                            ' by \x193}%(by)s') % {
mathieui's avatar
mathieui committed
789 790 791 792
                                'spec': char_kick,
                                'by': by,
                                'info_col': info_col
                            }
mathieui's avatar
mathieui committed
793 794 795
            else:
                kick_msg = ('\x191}%(spec)s \x193}You\x19%(info_col)s}'
                            ' have been kicked.') % {
mathieui's avatar
mathieui committed
796 797 798
                                'spec': char_kick,
                                'info_col': info_col
                            }
mathieui's avatar
mathieui committed
799 800 801
            self.core.disable_private_tabs(self.name, reason=kick_msg)
            self.disconnect()
            self.refresh_tab_win()
802
            self.core.tabs.current_tab.refresh_input()
mathieui's avatar
mathieui committed
803 804 805 806 807 808 809 810
            # try to auto-rejoin
            if config.get_by_tabname('autorejoin', self.general_jid):
                delay = config.get_by_tabname('autorejoin_delay',
                                              self.general_jid)
                delay = common.parse_str_to_secs(delay)
                if delay <= 0:
                    muc.join_groupchat(self.core, self.name, self.own_nick)
                else:
mathieui's avatar
mathieui committed
811 812 813 814
                    self.core.add_timed_event(
                        timed_events.DelayedEvent(delay, muc.join_groupchat,
                                                  self.core, self.name,
                                                  self.own_nick))
mathieui's avatar
mathieui committed
815 816 817 818 819 820 821 822 823 824
        else:
            if config.get_by_tabname('display_user_color_in_join_part',
                                     self.general_jid):
                color = dump_tuple(user.color)
            else:
                color = 3
            if by:
                kick_msg = ('\x191}%(spec)s \x19%(color)s}%(nick)s'
                            '\x19%(info_col)s} has been kicked by '
                            '\x193}%(by)s') % {
mathieui's avatar
mathieui committed
825 826 827 828 829 830
                                'spec': char_kick,
                                'nick': from_nick,
                                'color': color,
                                'by': by,
                                'info_col': info_col
                            }
mathieui's avatar
mathieui committed
831 832 833
            else:
                kick_msg = ('\x191}%(spec)s \x19%(color)s}%(nick)s'
                            '\x19%(info_col)s} has been kicked') % {
mathieui's avatar
mathieui committed
834 835 836 837 838
                                'spec': char_kick,
                                'nick': from_nick,
                                'color': color,
                                'info_col': info_col
                            }
mathieui's avatar
mathieui committed
839 840 841
        if reason is not None and reason.text:
            kick_msg += ('\x19%(info_col)s} Reason: \x196}'
                         '%(reason)s') % {
mathieui's avatar
mathieui committed
842 843 844
                             'reason': reason.text,
                             'info_col': info_col
                         }
mathieui's avatar
mathieui committed
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
        self.add_message(kick_msg, typ=2)

    def on_user_leave_groupchat(self, user, jid, status, from_nick, from_room):
        """
        When an user leaves a groupchat
        """
        self.users.remove(user)
        if self.own_nick == user.nick:
            # We are now out of the room.
            # Happens with some buggy (? not sure) servers
            self.disconnect()
            self.core.disable_private_tabs(from_room)
            self.refresh_tab_win()

        hide_exit_join = config.get_by_tabname('hide_exit_join',
                                               self.general_jid)

        if hide_exit_join <= -1 or user.has_talked_since(hide_exit_join):
            if config.get_by_tabname('display_user_color_in_join_part',
                                     self.general_jid):
                color = dump_tuple(user.color)
            else:
                color = 3
            info_col = dump_tuple(get_theme().COLOR_INFORMATION_TEXT)
            spec_col = dump_tuple(get_theme().COLOR_QUIT_CHAR)

            if not jid.full:
                leave_msg = ('\x19%(color_spec)s}%(spec)s \x19%(color)s}'
                             '%(nick)s\x19%(info_col)s} has left the '
                             'room') % {
mathieui's avatar
mathieui committed
875 876 877 878 879 880
                                 'nick': from_nick,
                                 'color': color,
                                 'spec': get_theme().CHAR_QUIT,
                                 'info_col': info_col,
                                 'color_spec': spec_col
                             }
mathieui's avatar
mathieui committed
881 882 883 884 885 886
            else:
                jid_col = dump_tuple(get_theme().COLOR_MUC_JID)
                leave_msg = ('\x19%(color_spec)s}%(spec)s \x19%(color)s}'
                             '%(nick)s\x19%(info_col)s} (\x19%(jid_col)s}'
                             '%(jid)s\x19%(info_col)s}) has left the '
                             'room') % {
mathieui's avatar
mathieui committed
887 888 889 890 891 892 893 894
                                 'spec': get_theme().CHAR_QUIT,
                                 'nick': from_nick,
                                 'color': color,
                                 'jid': jid.full,
                                 'info_col': info_col,
                                 'color_spec': spec_col,
                                 'jid_col': jid_col
                             }
mathieui's avatar
mathieui committed
895 896 897
            if status:
                leave_msg += ' (\x19o%s\x19%s})' % (status, info_col)
            self.add_message(leave_msg, typ=2)
mathieui's avatar
mathieui committed
898
        self.core.on_user_left_private_conversation(from_room, user, status)
mathieui's avatar
mathieui committed
899

mathieui's avatar
mathieui committed
900 901
    def on_user_change_status(self, user, from_nick, from_room, affiliation,
                              role, show, status):
mathieui's avatar
mathieui committed
902 903 904 905
        """
        When an user changes her status
        """
        # build the message
mathieui's avatar
mathieui committed
906 907
        display_message = False  # flag to know if something significant enough
        # to be displayed has changed
mathieui's avatar
mathieui committed
908 909 910 911 912 913 914
        if config.get_by_tabname('display_user_color_in_join_part',
                                 self.general_jid):
            color = dump_tuple(user.color)
        else:
            color = 3
        if from_nick == self.own_nick:
            msg = '\x19%(color)s}You\x19%(info_col)s} changed: ' % {
mathieui's avatar
mathieui committed
915 916 917
                'info_col': dump_tuple(get_theme().COLOR_INFORMATION_TEXT),
                'color': color
            }
mathieui's avatar
mathieui committed
918 919
        else:
            msg = '\x19%(color)s}%(nick)s\x19%(info_col)s} changed: ' % {
mathieui's avatar
mathieui committed
920 921 922 923
                'nick': from_nick,
                'color': color,
                'info_col': dump_tuple(get_theme().COLOR_INFORMATION_TEXT)
            }
mathieui's avatar
mathieui committed
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
        if affiliation != user.affiliation:
            msg += 'affiliation: %s, ' % affiliation
            display_message = True
        if role != user.role:
            msg += 'role: %s, ' % role
            display_message = True
        if show != user.show and show in SHOW_NAME:
            msg += 'show: %s, ' % SHOW_NAME[show]
            display_message = True
        if status != user.status:
            # if the user sets his status to nothing
            if status:
                msg += 'status: %s, ' % status
                display_message = True
            elif show in SHOW_NAME and show == user.show:
                msg += 'show: %s, ' % SHOW_NAME[show]
                display_message = True
        if not display_message:
            return
mathieui's avatar
mathieui committed
943
        msg = msg[:-2]  # remove the last ", "
mathieui's avatar
mathieui committed
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
        hide_status_change = config.get_by_tabname('hide_status_change',
                                                   self.general_jid)
        if hide_status_change < -1:
            hide_status_change = -1
        if ((hide_status_change == -1 or \
                user.has_talked_since(hide_status_change) or\
                user.nick == self.own_nick)\
                and\
                (affiliation != user.affiliation or\
                    role != user.role or\
                    show != user.show or\
                    status != user.status))\
                      or\
                        (affiliation != user.affiliation or\
                          role != user.role):
            # display the message in the room
            self._text_buffer.add_message(msg)
mathieui's avatar
mathieui committed
961 962
        self.core.on_user_changed_status_in_private(
            '%s/%s' % (from_room, from_nick), Status(show, status))
mathieui's avatar
mathieui committed
963 964 965 966 967 968 969 970 971 972 973 974
        self.users.remove(user)
        # finally, effectively change the user status
        user.update(affiliation, show, status, role)
        bisect.insort_left(self.users, user)

    def disconnect(self):
        """
        Set the state of the room as not joined, so
        we can know if we can join it, send messages to it, etc
        """
        self.presence_buffer = []
        self.users = []
975
        if self is not self.core.tabs.current_tab:
mathieui's avatar
mathieui committed
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
            self.state = 'disconnected'
        self.joined = False
        self.disable_self_ping_event()

    def get_single_line_topic(self):
        """
        Return the topic as a single-line string (for the window header)
        """
        return self.topic.replace('\n', '|')

    def log_message(self, txt, nickname, time=None, typ=1):
        """
        Log the messages in the archives, if it needs
        to be
        """
mathieui's avatar
mathieui committed
991
        if time is None and self.joined:  # don't log the history messages
mathieui's avatar
mathieui committed
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
            if not logger.log_message(self.name, nickname, txt, typ=typ):
                self.core.information('Unable to write in the log file',
                                      'Error')

    def get_user_by_name(self, nick):
        """
        Gets the user associated with the given nick, or None if not found
        """
        for user in self.users:
            if user.nick == nick:
                return user
        return None

    def add_message(self, txt, time=None, nickname=None, **kwargs):
        """
        Note that user can be None even if nickname is not None. It happens
        when we receive an history message said by someone who is not
        in the room anymore
        Return True if the message highlighted us. False otherwise.
        """

        # reset self-ping interval
        if self.self_ping_event:
            self.enable_self_ping_event()

        self.log_message(txt, nickname, time=time, typ=kwargs.get('typ', 1))
        args = dict()
        for key, value in kwargs.items():
            if key not in ('typ', 'forced_user'):
                args[key] = value
        if nickname is not None:
            user = self.get_user_by_name(nickname)
        else:
            user = None

        if user:
            user.set_last_talked(datetime.now())
            args['user'] = user
        if not user and kwargs.get('forced_user'):
            args['user'] = kwargs['forced_user']

        if (not time and nickname and nickname != self.own_nick
mathieui's avatar
mathieui committed
1034 1035 1036
                and self.state != 'current'):
            if (self.state != 'highlight'
                    and config.get_by_tabname('notify_messages', self.name)):
mathieui's avatar
mathieui committed
1037 1038 1039
                self.state = 'message'
        if time and not txt.startswith('/me'):
            txt = '\x19%(info_col)s}%(txt)s' % {
mathieui's avatar
mathieui committed
1040 1041 1042
                'txt': txt,
                'info_col': dump_tuple(get_theme().COLOR_LOG_MSG)
            }
mathieui's avatar
mathieui committed
1043 1044
        elif not nickname:
            txt = '\x19%(info_col)s}%(txt)s' % {
mathieui's avatar
mathieui committed
1045 1046 1047 1048
                'txt': txt,
                'info_col': dump_tuple(get_theme().COLOR_INFORMATION_TEXT)
            }
        elif not kwargs.get('highlight'):  # TODO
mathieui's avatar
mathieui committed
1049 1050 1051 1052
            args['highlight'] = self.do_highlight(txt, time, nickname)
        time = time or datetime.now()
        self._text_buffer.add_message(txt, time, nickname, **args)
        return args.get('highlight', False)
1053

mathieui's avatar
mathieui committed
1054 1055 1056 1057 1058 1059 1060 1061
    def modify_message(self,
                       txt,
                       old_id,
                       new_id,
                       time=None,
                       nickname=None,
                       user=None,
                       jid=None):
mathieui's avatar
mathieui committed
1062 1063
        self.log_message(txt, nickname, time=time, typ=1)
        highlight = self.do_highlight(txt, time, nickname, corrected=True)
mathieui's avatar
mathieui committed
1064 1065 1066 1067 1068 1069 1070 1071
        message = self._text_buffer.modify_message(
            txt,
            old_id,
            new_id,
            highlight=highlight,
            time=time,
            user=user,
            jid=jid)
mathieui's avatar
mathieui committed
1072 1073 1074 1075
        if message:
            self.text_win.modify_message(old_id, message)
            return highlight
        return False
1076

mathieui's avatar
mathieui committed
1077 1078
    def matching_names(self):
        return [(1, safeJID(self.name).user), (3, self.name)]
1079

mathieui's avatar
mathieui committed
1080
    def enable_self_ping_event(self):
mathieui's avatar
mathieui committed
1081 1082
        delay = config.get_by_tabname(
            "self_ping_delay", self.general_jid, default=0)
Link Mauve's avatar
Link Mauve committed
1083 1084 1085
        interval = int(
            config.get_by_tabname(
                "self_ping_interval", self.general_jid, default=delay))
1086
        if interval <= 0:  # use 0 or some negative value to disable it
1087
            return
mathieui's avatar
mathieui committed
1088
        self.disable_self_ping_event()
mathieui's avatar
mathieui committed
1089
        self.self_ping_event = timed_events.DelayedEvent(
1090
            interval, self.send_self_ping)
mathieui's avatar
mathieui committed
1091
        self.core.add_timed_event(self.self_ping_event)
1092

mathieui's avatar
mathieui committed
1093 1094 1095 1096
    def disable_self_ping_event(self):
        if self.self_ping_event is not None:
            self.core.remove_timed_event(self.self_ping_event)
            self.self_ping_event = None
1097

mathieui's avatar
mathieui committed
1098
    def send_self_ping(self):
Link Mauve's avatar
Link Mauve committed
1099 1100
        timeout = config.get_by_tabname(
            "self_ping_timeout", self.general_jid, default=60)
mathieui's avatar
mathieui committed
1101
        to = self.name + "/" + self.own_nick
mathieui's avatar
mathieui committed
1102 1103 1104 1105
        self.core.xmpp.plugin['xep_0199'].send_ping(
            jid=to,
            callback=self.on_self_ping_result,
            timeout_callback=self.on_self_ping_failed,
1106
            timeout=timeout)
1107

mathieui's avatar
mathieui committed
1108 1109 1110 1111
    def on_self_ping_result(self, iq):
        if iq["type"] == "error" and iq["error"]["condition"] != "feature-not-implemented":
            self.command_cycle(iq["error"]["text"] or "not in this room")
            self.core.refresh_window()
mathieui's avatar
mathieui committed
1112
        else:  # Re-send a self-ping in a few seconds
mathieui's avatar
mathieui committed
1113 1114 1115
            self.enable_self_ping_event()

    def search_for_color(self, nick):
1116
        """
mathieui's avatar
mathieui committed
1117 1118 1119
        Search for the color of a nick in the config file.
        Also, look at the colors of its possible aliases if nick_color_aliases
        is set.
1120
        """
mathieui's avatar
mathieui committed
1121 1122 1123
        color = config.get_by_tabname(nick, 'muc_colors')
        if color != '':
            return color
mathieui's avatar
mathieui committed
1124 1125
        nick_color_aliases = config.get_by_tabname('nick_color_aliases',
                                                   self.name)
mathieui's avatar
mathieui committed
1126 1127 1128 1129
        if nick_color_aliases:
            nick_alias = re.sub('^_*(.*?)_*$', '\\1', nick)
            color = config.get_by_tabname(nick_alias, 'muc_colors')
        return color
1130

mathieui's avatar
mathieui committed
1131 1132 1133
    def on_self_ping_failed(self, iq):
        self.command_cycle("the MUC server is not responding")
        self.core.refresh_window()
1134

mathieui's avatar
mathieui committed
1135 1136 1137 1138
########################## UI ONLY #####################################

    @refresh_wrapper.always
    def go_to_next_hl(self):
1139
        """