muctab.py 74.9 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
38


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


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 = {}
50

51
52
    def __init__(self, core, jid, nick, password=None):
        ChatTab.__init__(self, core, jid)
53
54
55
        self.joined = False
        self._state = 'disconnected'
        # our nick in the MUC
56
        self.own_nick = nick
57
        # self User object
58
        self.own_user = None
59
        self.name = jid
60
        self.password = password
61
        # buffered presences
62
        self.presence_buffer = []
63
        # userlist
64
        self.users = []
65
66
        # private conversations
        self.privates = []
67
        self.topic = ''
68
        self.topic_from = ''
69
70
71
        # We send active, composing and paused states to the MUC because
        # the chatstate may or may not be filtered by the MUC,
        # that’s not our problem.
72
73
74
75
        self.remote_wants_chatstates = True
        # Self ping event, so we can cancel it when we leave the room
        self.self_ping_event = None
        # UI stuff
76
77
78
79
80
81
82
        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()
83
84
        # List of ignored users
        self.ignores = []
85
        # keys
86
87
        self.register_keys()
        self.update_keys()
88
        # commands
89
        self.register_commands()
90
        self.update_commands()
91
        self.resize()
92
93
94

    @property
    def general_jid(self):
95
        return self.name
96

mathieui's avatar
mathieui committed
97
98
99
100
    def check_send_chat_state(self):
        "If we should send a chat state"
        return self.joined

101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
    @property
    def last_connection(self):
        last_message = self._text_buffer.last_message
        if last_message:
            return last_message.time
        return None

    def scroll_user_list_down(self):
        self.user_win.scroll_down()
        self.user_win.refresh(self.users)
        self.input.refresh()

    def cancel_config(self, form):
        """
        The user do not want to send his/her config, send an iq cancel
        """
117
        muc.cancel_config(self.core.xmpp, self.name)
118
119
120
121
122
123
        self.core.close_tab()

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

127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
    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:
            seconds = 0
        muc.join_groupchat(self.core, self.name, self.own_nick,
                           self.password,
                           status=status.message,
                           show=status.show,
                           seconds=seconds)
142

mathieui's avatar
mathieui committed
143
144
145
146
147
    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)
148

149
150
            if config.get_by_tabname('display_user_color_in_join_part',
                                     self.general_jid):
151
152
153
154
                color = dump_tuple(get_theme().COLOR_OWN_NICK)
            else:
                color = 3

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

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

182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
    def change_affiliation(self, nick_or_jid, affiliation, reason=''):
        """
        Change the affiliation of a nick or JID
        """
        def callback(iq):
            if iq['type'] == 'error':
                self.core.information("Could not set affiliation '%s' for '%s'." % (
                    affiliation, nick_or_jid), "Warning")
        if not self.joined:
            return

        valid_affiliations = ('outcast', 'none', 'member', 'admin', 'owner')
        if affiliation not in valid_affiliations:
            return self.core.information('The affiliation must be one of ' + ', '.join(valid_affiliations),
                                         'Error')
        if nick_or_jid in [user.nick for user in self.users]:
            res = muc.set_user_affiliation(self.core.xmpp, self.name,
                                           affiliation, nick=nick_or_jid,
                                           callback=callback, reason=reason)
        else:
            res = muc.set_user_affiliation(self.core.xmpp, self.name,
                                           affiliation, jid=safeJID(nick_or_jid),
                                           callback=callback, reason=reason)

    def change_role(self, nick, role, reason=''):
        """
        Change the role of a nick
        """
        def callback(iq):
            if iq['type'] == 'error':
                self.core.information("Could not set role '%s' for '%s'." % (
                    role, nick), "Warning")
        valid_roles = ('none', 'visitor', 'participant', 'moderator')

        if not self.joined or role not in valid_roles:
            return self.core.information('The role must be one of ' + ', '.join(valid_roles),
                                         'Error')

        if not safeJID(self.name + '/' + nick):
            return self.core.information('Invalid nick', 'Info')
        muc.set_user_role(self.core.xmpp, self.name, nick, reason, role,
                          callback=callback)

mathieui's avatar
mathieui committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
    @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)' % (
                            inf,
                            dump_tuple(theme.COLOR_MUC_JID),
                            user.jid,
                            inf)
        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') % {
                        '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 ''}
        self.add_message(info, typ=0)
        return True

mathieui's avatar
mathieui committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
    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)
                user_string = '\x19%s}(set by \x19%s}%s\x19%s})' % (
                        info_text, user_text, user.nick, info_text)
            else:
                user_string = self.topic_from
        else:
            user_string = ''

        self._text_buffer.add_message(
                "\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
286
287
288
289
290
291
292
293
294
295
296
    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() == ''
        empty_after = empty_after or (self.input.get_text().startswith('/')
                                      and not
                                      self.input.get_text().startswith('//'))
        self.send_composing_chat_state(empty_after)
        return False
297

mathieui's avatar
mathieui committed
298
299
300
301
    def get_nick(self):
        if not config.get('show_muc_jid'):
            return safeJID(self.name).user
        return self.name
302

mathieui's avatar
mathieui committed
303
304
    def get_text_window(self):
        return self.text_win
305

mathieui's avatar
mathieui committed
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
    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)
        if self.joined and config.get_by_tabname('send_chat_states',
                self.general_jid) and not self.input.get_text():
            self.send_chat_state('active')

    def handle_presence(self, presence):
331
        """
mathieui's avatar
mathieui committed
332
        Handle MUC presence
333
        """
mathieui's avatar
mathieui committed
334
335
336
        status_codes = set()
        for status_code in presence.xml.findall(STATUS_XPATH):
            status_codes.add(status_code.attrib['code'])
mathieui's avatar
mathieui committed
337
338
339
        if presence['type'] == 'error':
            self.core.room_error(presence, self.name)
        elif not self.joined:
mathieui's avatar
mathieui committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
            if '110' in status_codes:
               self.process_presence_buffer(presence)
            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)
        if self.core.current_tab() is self:
            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()
356

mathieui's avatar
mathieui committed
357
    def process_presence_buffer(self, last_presence):
358
        """
mathieui's avatar
mathieui committed
359
        Batch-process all the initial presences
360
        """
mathieui's avatar
mathieui committed
361
        deterministic = config.get_by_tabname('deterministic_nick_colors', self.name)
mathieui's avatar
mathieui committed
362

mathieui's avatar
mathieui committed
363
364
365
366
367
368
369
370
371
372
373
374
375
376
        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()
        if self.core.current_tab() is not self:
            self.refresh_tab_win()
            self.core.current_tab().input.refresh()
            self.core.doupdate()
377

mathieui's avatar
mathieui committed
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
    def handle_presence_unjoined(self, presence, deterministic, own=False):
        """
        Presence received while we are not in the room (before code=110)
        """
        from_nick, from_room, affiliation, show, status, role, jid, typ = dissect_presence(presence)
        user_color = self.search_for_color(from_nick)
        new_user = User(from_nick, affiliation, show,
                        status, role, jid, deterministic, user_color)
        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)
393

mathieui's avatar
mathieui committed
394
    def own_join(self, from_nick, new_user, status_codes):
395
        """
mathieui's avatar
mathieui committed
396
        Handle the last presence we received, entering the room
397
        """
mathieui's avatar
mathieui committed
398
399
400
401
402
403
404
405
406
407
408
409
        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'
        elif self != self.core.current_tab():
            self._state = 'joined'
        if (self.core.current_tab() is self
                and self.core.status.show not in ('xa', 'away')):
            self.send_chat_state('active')
        new_user.color = get_theme().COLOR_OWN_NICK
410

mathieui's avatar
mathieui committed
411
412
413
414
415
        if config.get_by_tabname('display_user_color_in_join_part',
                                 self.general_jid):
            color = dump_tuple(new_user.color)
        else:
            color = 3
416

mathieui's avatar
mathieui committed
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
        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)
        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,
                }
        self.add_message(enable_message, typ=2)
        self.core.enable_private_tabs(self.name, enable_message)
        if '201' in status_codes:
            self.add_message(
                    '\x19%(info_col)s}Info: The room '
                    'has been created' %
                       {'info_col': info_col},
                typ=0)
        if '170' in status_codes:
            self.add_message(
                    '\x19%(warn_col)s}Warning:\x19%(info_col)s}'
                    ' This room is publicly logged' %
                        {'info_col': info_col,
                         'warn_col': warn_col},
                typ=0)
        if '100' in status_codes:
            self.add_message(
                    '\x19%(warn_col)s}Warning:\x19%(info_col)s}'
                    ' This room is not anonymous.' %
                        {'info_col': info_col,
                         'warn_col': warn_col},
                typ=0)
452

mathieui's avatar
mathieui committed
453
    def handle_presence_joined(self, presence, status_codes):
454
        """
mathieui's avatar
mathieui committed
455
        Handle new presences when we are already in the room
456
        """
mathieui's avatar
mathieui committed
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
        from_nick, from_room, affiliation, show, status, role, jid, typ = dissect_presence(presence)
        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)
            self.on_user_join(from_nick, affiliation, show, status, role,
                              jid, user_color)
        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)
            self.core.on_user_left_private_conversation(from_room,
                                                        user, status)
            self.on_user_banned(presence, user, from_nick)
        elif kick:
            self.core.events.trigger('muc_kick', presence, self)
            self.core.on_user_left_private_conversation(from_room,
                                                        user, status)
            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':
            self.on_user_leave_groupchat(user, jid, status,
                                         from_nick, from_room)
        # status change
497
        else:
mathieui's avatar
mathieui committed
498
499
            self.on_user_change_status(user, from_nick, from_room,
                                       affiliation, role, show, status)
500

mathieui's avatar
mathieui committed
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
    def on_non_member_kicked(self):
        """We have been kicked because the MUC is members-only"""
        self.add_message(
                '\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)},
            typ=2)
        self.disconnect()

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

    def on_user_join(self, from_nick, affiliation, show, status, role, jid, color):
520
        """
mathieui's avatar
mathieui committed
521
        When a new user joins the groupchat
522
        """
mathieui's avatar
mathieui committed
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
        deterministic = config.get_by_tabname('deterministic_nick_colors', self.name)
        user = User(from_nick, affiliation,
                    show, status, role, jid, deterministic, color)
        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') % {
                            'nick': from_nick, 'spec': char_join,
                            'color': color,
                            'info_col': info_col,
                            'color_spec': spec_col,
                            }
            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') % {
                            '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,
                            }
            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):
        new_nick = presence.xml.find('{%s}x/{%s}item' % (NS_MUC_USER, NS_MUC_USER)
                                     ).attrib['nick']
        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)
566
        else:
mathieui's avatar
mathieui committed
567
568
569
570
571
572
573
574
            color = config.get_by_tabname(new_nick, 'muc_colors')
            if color != '':
                deterministic = config.get_by_tabname('deterministic_nick_colors',
                                                      self.name)
                user.change_color(color, deterministic)
        user.change_nick(new_nick)
        self.users.remove(user)
        bisect.insort_left(self.users, user)
575

mathieui's avatar
mathieui committed
576
577
578
        if config.get_by_tabname('display_user_color_in_join_part',
                                 self.general_jid):
            color = dump_tuple(user.color)
579
        else:
mathieui's avatar
mathieui committed
580
581
582
583
584
585
586
587
588
            color = 3
        info_col = dump_tuple(get_theme().COLOR_INFORMATION_TEXT)
        self.add_message('\x19%(color)s}%(old)s\x19%(info_col)s} is'
                         ' now known as \x19%(color)s}%(new)s' % {
                              'old':from_nick, 'new':new_nick,
                              'color':color, 'info_col': info_col},
                         typ=2)
        # rename the private tabs if needed
        self.core.rename_private_tabs(self.name, from_nick, user)
589

mathieui's avatar
mathieui committed
590
    def on_user_banned(self, presence, user, from_nick):
591
        """
mathieui's avatar
mathieui committed
592
        When someone is banned from a muc
593
        """
mathieui's avatar
mathieui committed
594
595
596
597
598
599
600
601
602
        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
603

mathieui's avatar
mathieui committed
604
605
        info_col = dump_tuple(get_theme().COLOR_INFORMATION_TEXT)
        char_kick = get_theme().CHAR_KICK
606

mathieui's avatar
mathieui committed
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
        if from_nick == self.own_nick: # we are banned
            if by:
                kick_msg = ('\x191}%(spec)s \x193}You\x19%(info_col)s}'
                            ' have been banned by \x194}%(by)s') % {
                                'spec': char_kick, 'by': by,
                                'info_col': info_col}
            else:
                kick_msg = ('\x191}%(spec)s \x193}You\x19'
                            '%(info_col)s} have been banned.') % {
                                'spec': char_kick, 'info_col': info_col}
            self.core.disable_private_tabs(self.name, reason=kick_msg)
            self.disconnect()
            self.refresh_tab_win()
            self.core.current_tab().input.refresh()
            self.core.doupdate()
            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:
                    self.core.add_timed_event(timed_events.DelayedEvent(
                                                  delay,
                                                  muc.join_groupchat,
                                                  self.core,
                                                  self.name,
                                                  self.own_nick))
635

mathieui's avatar
mathieui committed
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
        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') % {
                                'spec': char_kick, 'nick': from_nick,
                                'color': color, 'by': by,
                                'info_col': info_col}
            else:
                kick_msg = ('\x191}%(spec)s \x19%(color)s}%(nick)s'
                            '\x19%(info_col)s} has been banned') % {
                                'spec': char_kick, 'nick': from_nick,
                                'color': color, 'info_col': info_col}
        if reason is not None and reason.text:
            kick_msg += ('\x19%(info_col)s} Reason: \x196}'
                         '%(reason)s\x19%(info_col)s}') % {
                            'reason': reason.text, 'info_col': info_col}
        self.add_message(kick_msg, typ=2)

    def on_user_kicked(self, presence, user, from_nick):
662
        """
mathieui's avatar
mathieui committed
663
        When someone is kicked from a muc
664
        """
mathieui's avatar
mathieui committed
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
        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')
        if from_nick == self.own_nick: # we are kicked
            if by:
                kick_msg = ('\x191}%(spec)s \x193}You\x19'
                            '%(info_col)s} have been kicked'
                            ' by \x193}%(by)s') % {
                                 'spec': char_kick, 'by': by,
                                 'info_col': info_col}
            else:
                kick_msg = ('\x191}%(spec)s \x193}You\x19%(info_col)s}'
                            ' have been kicked.') % {
                                 'spec': char_kick,
                                 'info_col': info_col}
            self.core.disable_private_tabs(self.name, reason=kick_msg)
            self.disconnect()
            self.refresh_tab_win()
            self.core.current_tab().input.refresh()
            self.core.doupdate()
            # 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:
                    self.core.add_timed_event(timed_events.DelayedEvent(
                        delay,
                        muc.join_groupchat,
                        self.core,
                        self.name,
                        self.own_nick))
        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') % {
                                'spec': char_kick, 'nick':from_nick,
                                'color':color, 'by':by, 'info_col': info_col}
            else:
                kick_msg = ('\x191}%(spec)s \x19%(color)s}%(nick)s'
                            '\x19%(info_col)s} has been kicked') % {
                                'spec': char_kick, 'nick': from_nick,
                                'color':color, 'info_col': info_col}
        if reason is not None and reason.text:
            kick_msg += ('\x19%(info_col)s} Reason: \x196}'
                         '%(reason)s') % {
                            'reason': reason.text, 'info_col': info_col}
        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') % {
                                  'nick':from_nick, 'color':color,
                                  'spec':get_theme().CHAR_QUIT,
                                  'info_col': info_col,
                                  'color_spec': spec_col}
            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') % {
                                  '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}
            if status:
                leave_msg += ' (\x19o%s\x19%s})' % (status, info_col)
            self.add_message(leave_msg, typ=2)
        self.core.on_user_left_private_conversation(from_room, user,
                                                    status)

    def on_user_change_status(
            self, user, from_nick, from_room, affiliation, role, show, status):
        """
        When an user changes her status
        """
        # build the message
        display_message = False # flag to know if something significant enough
                                # to be displayed has changed
        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: ' % {
                  'info_col': dump_tuple(get_theme().COLOR_INFORMATION_TEXT),
                  'color': color}
        else:
            msg = '\x19%(color)s}%(nick)s\x19%(info_col)s} changed: ' % {
                  'nick': from_nick, 'color': color,
                  'info_col': dump_tuple(get_theme().COLOR_INFORMATION_TEXT)}
        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
        msg = msg[:-2] # remove the last ", "
        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)
        self.core.on_user_changed_status_in_private('%s/%s' %
                                                      (from_room, from_nick),
                                                    Status(show, status))
        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 = []
        if self is not self.core.current_tab():
            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
        """
        if time is None and self.joined:    # don't log the history messages
            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
                    and self.state != 'current'):
            if (self.state != 'highlight' and
                    config.get_by_tabname('notify_messages', self.name)):
                self.state = 'message'
        if time and not txt.startswith('/me'):
            txt = '\x19%(info_col)s}%(txt)s' % {
                    'txt': txt,
                    'info_col': dump_tuple(get_theme().COLOR_LOG_MSG)}
        elif not nickname:
            txt = '\x19%(info_col)s}%(txt)s' % {
                    'txt': txt,
                    'info_col': dump_tuple(get_theme().COLOR_INFORMATION_TEXT)}
        elif not kwargs.get('highlight'):                   # TODO
            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)
927

mathieui's avatar
mathieui committed
928
929
930
931
932
933
934
935
936
937
938
939
    def modify_message(self, txt, old_id, new_id,
                       time=None, nickname=None, user=None, jid=None):
        self.log_message(txt, nickname, time=time, typ=1)
        highlight = self.do_highlight(txt, time, nickname, corrected=True)
        message = self._text_buffer.modify_message(txt, old_id, new_id,
                                                   highlight=highlight,
                                                   time=time, user=user,
                                                   jid=jid)
        if message:
            self.text_win.modify_message(old_id, message)
            return highlight
        return False
940

mathieui's avatar
mathieui committed
941
942
    def matching_names(self):
        return [(1, safeJID(self.name).user), (3, self.name)]
943

mathieui's avatar
mathieui committed
944
945
946
    def enable_self_ping_event(self):
        delay = config.get_by_tabname("self_ping_delay", self.general_jid, default=0)
        if delay <= 0:          # use 0 or some negative value to disable it
947
            return
mathieui's avatar
mathieui committed
948
949
950
        self.disable_self_ping_event()
        self.self_ping_event = timed_events.DelayedEvent(delay, self.send_self_ping)
        self.core.add_timed_event(self.self_ping_event)
951

mathieui's avatar
mathieui committed
952
953
954
955
    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
956

mathieui's avatar
mathieui committed
957
958
959
960
961
962
    def send_self_ping(self):
        to = self.name + "/" + self.own_nick
        self.core.xmpp.plugin['xep_0199'].send_ping(jid=to,
                                                    callback=self.on_self_ping_result,
                                                    timeout_callback=self.on_self_ping_failed,
                                                    timeout=60)
963

mathieui's avatar
mathieui committed
964
965
966
967
968
969
970
971
    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()
        else:                   # Re-send a self-ping in a few seconds
            self.enable_self_ping_event()

    def search_for_color(self, nick):
972
        """
mathieui's avatar
mathieui committed
973
974
975
        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.
976
        """
mathieui's avatar
mathieui committed
977
978
979
980
981
982
983
984
        color = config.get_by_tabname(nick, 'muc_colors')
        if color != '':
            return color
        nick_color_aliases = config.get_by_tabname('nick_color_aliases', self.name)
        if nick_color_aliases:
            nick_alias = re.sub('^_*(.*?)_*$', '\\1', nick)
            color = config.get_by_tabname(nick_alias, 'muc_colors')
        return color
985

mathieui's avatar
mathieui committed
986
987
988
    def on_self_ping_failed(self, iq):
        self.command_cycle("the MUC server is not responding")
        self.core.refresh_window()
989

mathieui's avatar
mathieui committed
990
991
992
993
########################## UI ONLY #####################################

    @refresh_wrapper.always
    def go_to_next_hl(self):
994
        """
mathieui's avatar
mathieui committed
995
        Go to the next HL in the room, or the last
996
        """
mathieui's avatar
mathieui committed
997
        self.text_win.next_highlight()
998

mathieui's avatar
mathieui committed
999
1000
    @refresh_wrapper.always
    def go_to_prev_hl(self):
1001
        """
mathieui's avatar
mathieui committed
1002
        Go to the previous HL in the room, or the first
1003
        """
mathieui's avatar
mathieui committed
1004
        self.text_win.previous_highlight()
1005

mathieui's avatar
mathieui committed
1006
1007
1008
1009
    def scroll_user_list_up(self):
        self.user_win.scroll_up()
        self.user_win.refresh(self.users)
        self.input.refresh()
1010
1011
1012
1013
1014

    def resize(self):
        """
        Resize the whole window. i.e. all its sub-windows
        """
1015
        self.need_resize = False
1016
        if config.get('hide_user_list') or self.size.tab_degrade_x:
1017
1018
            text_width = self.width
        else:
mathieui's avatar
mathieui committed
1019
            text_width = (self.width // 10) * 9
1020

mathieui's avatar
mathieui committed
1021
1022
1023
1024
1025
1026
        if self.size.tab_degrade_y:
            tab_win_height = 0
            info_win_height = 0
        else:
            tab_win_height = Tab.tab_win_height()
            info_win_height = self.core.information_win_size
1027
1028


mathieui's avatar
mathieui committed
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
        self.user_win.resize(self.height - 3 - info_win_height
                                - tab_win_height,
                             self.width - (self.width // 10) * 9 - 1,
                             1,
                             (self.width // 10) * 9 + 1)
        self.v_separator.resize(self.height - 3 - info_win_height - tab_win_height,
                                1, 1, 9 * (self.width // 10))

        self.topic_win.resize(1, self.width, 0, 0)

        self.text_win.resize(self.height - 3 - info_win_height
                                - tab_win_height,
                             text_width, 1, 0)
        self.text_win.rebuild_everything(self._text_buffer)
        self.info_header.resize(1, self.width,
                                self.height - 2 - info_win_height
                                    - tab_win_height,
                                0)
        self.input.resize(1, self.width, self.height-1, 0)

    def refresh(self):
        if self.need_resize:
            self.resize()
        log.debug('  TAB   Refresh: %s', self.__class__.__name__)
        if config.get('hide_user_list') or self.size.tab_degrade_x:
            display_user_list = False
1055
        else:
mathieui's avatar
mathieui committed
1056
1057
            display_user_list = True
        display_info_win = not self.size.tab_degrade_y
1058

mathieui's avatar
mathieui committed
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
        self.topic_win.refresh(self.get_single_line_topic())
        self.text_win.refresh()
        if display_user_list:
            self.v_separator.refresh()
            self.user_win.refresh(self.users)
        self.info_header.refresh(self, self.text_win, user=self.own_user)
        self.refresh_tab_win()
        if display_info_win:
            self.info_win.refresh()
        self.input.refresh()
1069
1070
1071
1072

    def on_info_win_size_changed(self):
        if self.core.information_win_size >= self.height-3:
            return
1073
        if config.get("hide_user_list"):
1074
1075
1076
            text_width = self.width
        else:
            text_width = (self.width//10)*9
1077
1078
1079
1080
1081
        self.user_win.resize(self.height - 3 - self.core.information_win_size
                                - Tab.tab_win_height(),
                             self.width - (self.width // 10) * 9 - 1,
                             1,
                             (self.width // 10) * 9 + 1)
1082
1083
        self.v_separator.resize(self.height - 3 - self.core.information_win_size - Tab.tab_win_height(),
                                1, 1, 9 * (self.width // 10))
1084
1085
1086
1087
1088
1089
1090
        self.text_win.resize(self.height - 3 - self.core.information_win_size
                                - Tab.tab_win_height(),
                             text_width, 1, 0)
        self.info_header.resize(1, self.width,
                                self.height-2-self.core.information_win_size
                                    - Tab.tab_win_height(),
                                0)
mathieui's avatar
mathieui committed
1091
    def do_highlight(self, txt, time, nickname, corrected=False):
1092
        """
mathieui's avatar
mathieui committed
1093
        Set the tab color and returns the nick color
1094
        """
mathieui's avatar
mathieui committed
1095
1096
1097
1098
1099
1100
1101
        highlighted = False
        if (not time or corrected) and nickname and nickname != self.own_nick and self.joined:

            if re.search(r'\b' + self.own_nick.lower() + r'\b', txt.lower()):
                if self.state != 'current':
                    self.state = 'highlight'
                highlighted = True
1102
            else:
mathieui's avatar
mathieui committed
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
                highlight_words = config.get_by_tabname('highlight_on',
                                                        self.general_jid)
                highlight_words = highlight_words.split(':')
                for word in highlight_words:
                    if word and word.lower() in txt.lower():
                        if self.state != 'current':
                            self.state = 'highlight'
                        highlighted = True
                        break
        if highlighted:
            beep_on = config.get('beep_on').split()
            if 'highlight' in beep_on and 'message' not in beep_on:
                if not config.get_by_tabname('disable_beep', self.name):
                    curses.beep()
        return highlighted

########################## COMMANDS ####################################

    @command_args_parser.quoted(1, 1, [''])
    def command_invite(self, args):
        """/invite <jid> [reason]"""
        if args is None:
            return self.core.command.help('invite')
        jid, reason = args
        self.core.command.invite('%s %s "%s"' % (jid, self.name, reason))

    @command_args_parser.quoted(1)
    def command_info(self, args):
        """
        /info <nick>
        """
        if args is None:
            return self.core.command.help('info')
        nick = args[0]
mathieui's avatar
mathieui committed
1137
1138
        if not self.print_info(nick):
            self.core.information("Unknown user: %s" % nick, "Error")
mathieui's avatar
mathieui committed
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149

    @command_args_parser.quoted(0)
    def command_configure(self, ignored):
        """
        /configure
        """
        def on_form_received(form):
            if not form:
                self.core.information(
                    'Could not retrieve the configuration form',
                    'Error')
1150
                return
mathieui's avatar
mathieui committed
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
            self.core.open_new_form(form, self.cancel_config, self.send_config)

        fixes.get_room_form(self.core.xmpp, self.name, on_form_received)

    @command_args_parser.raw
    def command_cycle(self, msg):
        """/cycle [reason]"""
        self.leave_room(msg)
        self.join()

    @command_args_parser.quoted(0, 1, [''])
    def command_recolor(self, args):
        """
        /recolor [random]
        Re-assign color to the participants of the room
        """
        deterministic = config.get_by_tabname('deterministic_nick_colors', self.name)
        if deterministic:
            for user in self.users:
                if user.nick == self.own_nick:
                    continue
                color = self.search_for_color(user.nick)
                if color != '':
                    continue
                user.set_deterministic_color()
            if args[0] == 'random':
                self.core.information('"random" was provided, but poezio is '
                                      'configured to use deterministic colors',
                                      'Warning')
            self.user_win.refresh(self.users)
            self.input.refresh()
            return
        compare_users = lambda x: x.last_talked
        users = list(self.users)
        sorted_users = sorted(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.nick == self.own_nick:
                sorted_users.remove(user)
                user.color = get_theme().COLOR_OWN_NICK
            elif color != '':
                sorted_users.remove(user)
                user.change_color(color, deterministic)
        colors = list(get_theme().LIST_COLOR_NICKNAMES)
        if args[0] == 'random':
            random.shuffle(colors)
        for i, user in enumerate(sorted_users):
            user.color = colors[i % len(colors)]
        self.text_win.rebuild_everything(self._text_buffer)
        self.user_win.refresh(self.users)
        self.text_win.refresh()
        self.input.refresh()

    @command_args_parser.quoted(2, 2, [''])
    def command_color(self, args):
        """
        /color <nick> <color>
        Fix a color for a nick.
        Use "unset" instead of a color to remove the attribution.
        User "random" to attribute a random color.
        """
        if args is None:
            return self.core.command.help('color')
        nick = args[0]
        color = args[1].lower()
        user = self.get_user_by_name(nick)
        if color not in xhtml.colors and color not in ('unset', 'random'):
            return self.core.information("Unknown color: %s" % color, 'Error')
        if user and user.nick == self.own_nick:
            return self.core.information("You cannot change the color of your"
                                         " own nick.", 'Error')
        if color == 'unset':
            if config.remove_and_save(nick, 'muc_colors'):
                self.core.information('Color for nick %s unset' % (nick))
1228
        else:
mathieui's avatar
mathieui committed
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
            if color == 'random':
                color = random.choice(list(xhtml.colors))
            if user:
                user.change_color(color)
            config.set_and_save(nick, color, 'muc_colors')
            nick_color_aliases = config.get_by_tabname('nick_color_aliases', self.name)
            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)
            self.user_win.refresh(self.users)
1246
1247
1248
            self.text_win.refresh()
            self.input.refresh()

mathieui's avatar
mathieui committed
1249
1250
    @command_args_parser.quoted(1)
    def command_version(self, args):
1251
        """
mathieui's avatar
mathieui committed
1252
        /version <jid or nick>
1253
        """
mathieui's avatar
mathieui committed
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
        def callback(res):
            if not res:
                return self.core.information('Could not get the software '
                                             'version from %s' % (jid,),
                                             'Warning')
            version = '%s is running %s version %s on %s' % (
                         jid,
                         res.get('name') or 'an unknown software',
                         res.get('version') or 'unknown',
                         res.get('os') or 'an unknown platform')
            self.core.information(version, 'Info')
        if args is None:
            return self.core.command.help('version')
        nick = args[0]
        if nick in [user.nick for user in self.users]:
            jid = safeJID(self.name).bare
            jid = safeJID(jid + '/' + nick)
        else:
            jid = safeJID(nick)
        fixes.get_version(self.core.xmpp, jid,
                          callback=callback)
1275

mathieui's avatar
mathieui committed
1276
1277
    @command_args_parser.quoted(1)
    def command_nick(self, args):
1278
        """
mathieui's avatar
mathieui committed
1279
        /nick <nickname>
1280
        """
mathieui's avatar
mathieui committed
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
        if args is None:
            return self.core.command.help('nick')
        nick = args[0]
        if not self.joined:
            return self.core.information('/nick only works in joined rooms',
                                         'Info')
        current_status = self.core.get_status()
        if not safeJID(self.name + '/' + nick):
            return self.core.information('Invalid nick', 'Info')
        muc.change_nick(self.core, self.name, nick,
                        current_status.message,
                        current_status.show)
1293

mathieui's avatar
mathieui committed
1294
1295
    @command_args_parser.quoted(0, 1, [''])
    def command_part(self, args):
1296
        """
mathieui's avatar
mathieui committed
1297
        /part [msg]
1298
        """
mathieui's avatar
mathieui committed
1299
1300
1301
1302
1303
        message = args[0]
        self.leave_room(message)
        if self == self.core.current_tab():
            self.refresh()
        self.core.doupdate()
1304

mathieui's avatar
mathieui committed
1305
1306
    @command_args_parser.raw
    def command_close(self, msg):
1307
        """
mathieui's avatar
mathieui committed
1308
        /close [msg]
1309
        """
mathieui's avatar
mathieui committed
1310
1311
        self.command_part(msg)
        self.core.close_tab(self)
1312

mathieui's avatar
mathieui committed
1313
1314
1315
    def on_close(self):
        super().on_close()
        self.command_part('')
1316

mathieui's avatar
mathieui committed
1317
1318
    @command_args_parser.quoted(1, 1)
    def command_query(self, args):
1319
        """
mathieui's avatar
mathieui committed
1320
        /query <nick> [message]
1321
        """
mathieui's avatar
mathieui committed
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
        if args is None:
            return  self.core.command.help('query')
        nick = args[0]
        r = None
        for user in self.users:
            if user.nick == nick:
                r = self.core.open_private_window(self.name, user.nick)
        if r and len(args) == 2:
            msg = args[1]
            self.core.current_tab().command_say(
                    xhtml.convert_simple_to_full_colors(msg))
        if not r:
            self.core.information("Cannot find user: %s" % nick, 'Error')

    @command_args_parser.raw
    def command_topic(self, subject):
        """
        /topic [new topic]
        """
        if not subject:
mathieui's avatar
mathieui committed
1342
1343
1344
            self.show_topic()
        else:
            self.change_topic(subject)
1345

mathieui's avatar
mathieui committed
1346
1347
    @command_args_parser.quoted(0)
    def command_names(self, args):
1348
        """
mathieui's avatar
mathieui committed
1349
        /names
1350
        """
mathieui's avatar
mathieui committed
1351
1352
        if not self.joined:
            return
1353

mathieui's avatar
mathieui committed
1354
1355
1356
1357
1358
1359
        aff = {
                'owner': get_theme().CHAR_AFFILIATION_OWNER,
                'admin': get_theme().CHAR_AFFILIATION_ADMIN,
                'member': get_theme().CHAR_AFFILIATION_MEMBER,
                'none': get_theme().CHAR_AFFILIATION_NONE,
                }
1360

mathieui's avatar
mathieui committed
1361
1362
1363
1364
1365
        colors = {}
        colors["visitor"] = dump_tuple(get_theme().COLOR_USER_VISITOR)
        colors["moderator"] = dump_tuple(get_theme().COLOR_USER_MODERATOR)
        colors["participant"] = dump_tuple(get_theme().COLOR_USER_PARTICIPANT)
        color_other = dump_tuple(get_theme().COLOR_USER_NONE)
1366

mathieui's avatar
mathieui committed
1367
1368
1369
1370
1371
1372
1373
        buff = ['Users: %s \n' % len(self.users)]
        for user in self.users:
            affiliation = aff.get(user.affiliation,
                                  get_theme().CHAR_AFFILIATION_NONE)
            color = colors.get(user.role, color_other)
            buff.append('\x19%s}%s\x19o\x19%s}%s\x19o' % (
                color, affiliation, dump_tuple(user.color), user.nick))
1374

mathieui's avatar
mathieui committed
1375
1376
        buff.append('\n')
        message = ' '.join(buff)
1377

mathieui's avatar
mathieui committed
1378
1379
1380
1381
1382
1383
        self._text_buffer.add_message(message)
        self.text_win.refresh()
        self.input.refresh()

    @command_args_parser.quoted(1, 1)
    def command_kick(self, args):
1384
        """
mathieui's avatar
mathieui committed
1385
        /kick <nick> [reason]
1386
        """
mathieui's avatar
mathieui committed
1387
1388
1389
        if args is None:
            return self.core.command.help('kick')
        if len(args) == 2:
1390
            reason = args[1]
1391
        else:
1392
1393
1394
            reason = ''
        nick = args[0]
        self.change_role(nick, 'none', reason)
mathieui's avatar
mathieui committed
1395
1396
1397
1398
1399
1400
1401
1402
1403

    @command_args_parser.quoted(1, 1)
    def command_ban(self, args):
        """
        /ban <nick> [reason]
        """
        if args is None:
            return self.core.command.help('ban')
        nick = args[0]
1404
1405
        msg = args[1] if len(args) == 2 else ''
        self.change_affiliation(nick, 'outcast', msg)
1406

mathieui's avatar
mathieui committed
1407
1408
    @command_args_parser.quoted(2, 1, [''])
    def command_role(self, args):
1409
        """
mathieui's avatar
mathieui committed
1410
1411
1412
        /role <nick> <role> [reason]
        Changes the role of an user
        roles can be: none, visitor, participant, moderator
1413
        """
mathieui's avatar
mathieui committed
1414
1415
1416
        def callback(iq):
            if iq['type'] == 'error':
                self.core.room_error(iq, self.name)
1417

mathieui's avatar
mathieui committed
1418
1419
        if args is None:
            return self.core.command.help('role')
1420

mathieui's avatar
mathieui committed
1421
        nick, role, reason = args[0], args[1].lower(), args[2]
1422
        self.change_role(nick, role, reason)
mathieui's avatar
mathieui committed
1423
1424
1425

    @command_args_parser.quoted(2)
    def command_affiliation(self, args):
1426
        """
mathieui's avatar
mathieui committed
1427
1428
1429
        /affiliation <nick> <role>
        Changes the affiliation of an user
        affiliations can be: outcast, none, member, admin, owner
1430
        """
mathieui's avatar
mathieui committed
1431
1432
1433
1434
1435
1436
1437
1438
        def callback(iq):
            if iq['type']