privatetab.py 14.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
"""
Module for the PrivateTab

A PrivateTab is a private conversation opened with someone from a MUC
(see muctab.py). The conversation happens with both JID being relative
to the MUC (room@server/nick1 and room@server/nick2).

This tab references his parent room, and is modified to keep track of
both participant’s nicks. It also has slightly different features than
the ConversationTab (such as tab-completion on nicks from the room).

"""
13
import curses
14 15
import logging
from typing import Dict, Callable
16
from xml.etree import cElementTree as ET
17

18 19
from slixmpp import JID

mathieui's avatar
mathieui committed
20
from poezio.tabs import OneToOneTab, MucTab, Tab
21

22 23 24
from poezio import windows
from poezio import xhtml
from poezio.config import config
25
from poezio.core.structs import Command
26 27 28 29
from poezio.decorators import refresh_wrapper
from poezio.logger import logger
from poezio.theming import get_theme, dump_tuple
from poezio.decorators import command_args_parser
30

31 32
log = logging.getLogger(__name__)

mathieui's avatar
mathieui committed
33

34
class PrivateTab(OneToOneTab):
35
    """
36
    The tab containing a private conversation (someone from a MUC)
37
    """
38 39
    plugin_commands = {}  # type: Dict[str, Command]
    plugin_keys = {}  # type: Dict[str, Callable]
40
    message_type = 'chat'
41
    additional_information = {}  # type: Dict[str, Callable[[str], str]]
mathieui's avatar
mathieui committed
42

43 44
    def __init__(self, core, jid, nick):
        OneToOneTab.__init__(self, core, jid)
45 46 47 48 49 50 51 52
        self.own_nick = nick
        self.text_win = windows.TextWin()
        self._text_buffer.add_window(self.text_win)
        self.info_header = windows.PrivateInfoWin()
        self.input = windows.MessageInput()
        # keys
        self.key_func['^I'] = self.completion
        # commands
mathieui's avatar
mathieui committed
53 54 55 56
        self.register_command(
            'info',
            self.command_info,
            desc=
Kim Alvefur's avatar
Kim Alvefur committed
57
            'Display some information about the user in the MUC: their role, affiliation, status and status message.',
mathieui's avatar
mathieui committed
58 59 60 61 62 63 64
            shortdesc='Info about the user.')
        self.register_command(
            'version',
            self.command_version,
            desc=
            'Get the software version of the current interlocutor (usually its XMPP client and Operating System).',
            shortdesc='Get the software version of a jid.')
65
        self.resize()
66
        self.parent_muc = self.core.tabs.by_name_and_class(self.jid.bare, MucTab)
67 68 69 70
        self.on = True
        self.update_commands()
        self.update_keys()

71
    def remote_user_color(self):
72
        user = self.parent_muc.get_user_by_name(self.jid.resource)
73
        if user:
mathieui's avatar
mathieui committed
74
            return dump_tuple(user.color)
75 76
        return super().remote_user_color()

77 78
    @property
    def general_jid(self):
79
        return self.jid
80

81
    def get_dest_jid(self):
82
        return self.jid
83

84 85 86 87
    @property
    def nick(self):
        return self.get_nick()

88
    def ack_message(self, msg_id: str, msg_jid: JID):
mathieui's avatar
mathieui committed
89 90 91
        if JID(msg_jid).bare == self.core.xmpp.boundjid.bare:
            msg_jid = JID(self.jid.bare)
            msg_jid.resource = self.own_nick
92 93
        super().ack_message(msg_id, msg_jid)

94
    @staticmethod
95
    @refresh_wrapper.always
96 97 98 99
    def add_information_element(plugin_name, callback):
        """
        Lets a plugin add its own information to the PrivateInfoWin
        """
100
        PrivateTab.additional_information[plugin_name] = callback
101 102

    @staticmethod
103
    @refresh_wrapper.always
104
    def remove_information_element(plugin_name):
105
        del PrivateTab.additional_information[plugin_name]
106 107 108 109 110

    def log_message(self, txt, nickname, time=None, typ=1):
        """
        Log the messages in the archives.
        """
mathieui's avatar
mathieui committed
111
        if not logger.log_message(
112
                self.jid.full, nickname, txt, date=time, typ=typ):
113
            self.core.information('Unable to write in the log file', 'Error')
114 115

    def on_close(self):
116
        super().on_close()
117 118 119 120 121 122 123 124 125 126 127 128 129
        self.parent_muc.privates.remove(self)

    def completion(self):
        """
        Called when Tab is pressed, complete the nickname in the input
        """
        if self.complete_commands(self.input):
            return

        # If we are not completing a command or a command's argument, complete a nick
        compare_users = lambda x: x.last_talked
        word_list = [user.nick for user in sorted(self.parent_muc.users, key=compare_users, reverse=True)\
                         if user.nick != self.own_nick]
130
        after = config.get('after_completion') + ' '
131 132 133 134 135 136 137
        input_pos = self.input.pos
        if ' ' not in self.input.get_text()[:input_pos] or (self.input.last_completion and\
                     self.input.get_text()[:input_pos] == self.input.last_completion + after):
            add_after = after
        else:
            add_after = ''
        self.input.auto_completion(word_list, add_after, quotify=False)
mathieui's avatar
mathieui committed
138 139 140
        empty_after = self.input.get_text() == '' or (
            self.input.get_text().startswith('/')
            and not self.input.get_text().startswith('//'))
141 142
        self.send_composing_chat_state(empty_after)

143
    @refresh_wrapper.always
144
    @command_args_parser.raw
145 146 147
    def command_say(self, line, attention=False, correct=False):
        if not self.on:
            return
mathieui's avatar
mathieui committed
148 149
        our_jid = JID(self.jid.bare)
        our_jid.resource = self.own_nick
150 151
        msg = self.core.xmpp.make_message(
            mto=self.jid.full,
mathieui's avatar
mathieui committed
152
            mfrom=our_jid,
153
        )
154 155
        msg['type'] = 'chat'
        msg['body'] = line
156 157
        x = ET.Element('{http://jabber.org/protocol/muc#user}x')
        msg.append(x)
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
        # trigger the event BEFORE looking for colors.
        # This lets a plugin insert \x19xxx} colors, that will
        # be converted in xhtml.
        self.core.events.trigger('private_say', msg, self)
        if not msg['body']:
            return
        user = self.parent_muc.get_user_by_name(self.own_nick)
        replaced = False
        if correct or msg['replace']['id']:
            msg['replace']['id'] = self.last_sent_message['id']
        else:
            del msg['replace']

        if msg['body'].find('\x19') != -1:
            msg.enable('html')
            msg['html']['body'] = xhtml.poezio_colors_to_html(msg['body'])
            msg['body'] = xhtml.clean_text(msg['body'])
175
        if config.get_by_tabname('send_chat_states', self.general_jid):
176 177
            needed = 'inactive' if self.inactive else 'active'
            msg['chat_state'] = needed
178
        if attention:
179 180 181 182
            msg['attention'] = True
        self.core.events.trigger('private_say_after', msg, self)
        if not msg['body']:
            return
Maxime Buquet's avatar
Maxime Buquet committed
183
        self.set_last_sent_message(msg, correct=correct)
mathieui's avatar
mathieui committed
184
        self.core.handler.on_groupchat_private_message(msg, sent=True)
185
        msg._add_receipt = True
186 187 188
        msg.send()
        self.cancel_paused_delay()

189 190
    @command_args_parser.quoted(0, 1)
    def command_version(self, args):
191 192 193
        """
        /version
        """
194
        if args:
195
            return self.core.command.version(args[0])
196
        jid = self.jid.full
197 198
        self.core.xmpp.plugin['xep_0092'].get_version(
            jid, callback=self.core.handler.on_version_result)
199

200
    @command_args_parser.quoted(0, 1)
201 202 203 204
    def command_info(self, arg):
        """
        /info
        """
mathieui's avatar
mathieui committed
205 206
        if arg and arg[0]:
            self.parent_muc.command_info(arg[0])
207
        else:
208
            user = self.jid.resource
209 210 211
            self.parent_muc.command_info(user)

    def resize(self):
212 213
        self.need_resize = False

214 215 216 217 218 219 220
        if self.size.tab_degrade_y:
            info_win_height = 0
            tab_win_height = 0
        else:
            info_win_height = self.core.information_win_size
            tab_win_height = Tab.tab_win_height()

mathieui's avatar
mathieui committed
221 222 223
        self.text_win.resize(
            self.height - 2 - info_win_height - tab_win_height, self.width, 0,
            0)
224
        self.text_win.rebuild_everything(self._text_buffer)
mathieui's avatar
mathieui committed
225 226 227 228
        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)
229 230 231 232

    def refresh(self):
        if self.need_resize:
            self.resize()
233
        log.debug('  TAB   Refresh: %s', self.__class__.__name__)
234 235
        display_info_win = not self.size.tab_degrade_y

236
        self.text_win.refresh()
237
        self.info_header.refresh(self.jid.full, self.text_win, self.chatstate,
238
                                 PrivateTab.additional_information)
239 240 241
        if display_info_win:
            self.info_win.refresh()

242 243 244 245
        self.refresh_tab_win()
        self.input.refresh()

    def refresh_info_header(self):
246
        self.info_header.refresh(self.jid.full, self.text_win, self.chatstate,
mathieui's avatar
mathieui committed
247
                                 PrivateTab.additional_information)
248 249 250
        self.input.refresh()

    def get_nick(self):
251
        return self.jid.resource
252 253 254 255 256 257 258 259

    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)
        if not self.on:
            return False
mathieui's avatar
mathieui committed
260 261 262
        empty_after = self.input.get_text() == '' or (
            self.input.get_text().startswith('/')
            and not self.input.get_text().startswith('//'))
263
        tab = self.core.tabs.by_name_and_class(self.jid.bare, MucTab)
264 265 266 267 268
        if tab and tab.joined:
            self.send_composing_chat_state(empty_after)
        return False

    def on_lose_focus(self):
269 270 271 272 273
        if self.input.text:
            self.state = 'nonempty'
        else:
            self.state = 'normal'

274 275
        self.text_win.remove_line_separator()
        self.text_win.add_line_separator(self._text_buffer)
276
        tab = self.core.tabs.by_name_and_class(self.jid.bare, MucTab)
mathieui's avatar
mathieui committed
277 278
        if tab and tab.joined and config.get_by_tabname(
                'send_chat_states', self.general_jid) and self.on:
279 280 281 282 283 284
            self.send_chat_state('inactive')
        self.check_scrolled()

    def on_gain_focus(self):
        self.state = 'current'
        curses.curs_set(1)
285
        tab = self.core.tabs.by_name_and_class(self.jid.bare, MucTab)
mathieui's avatar
mathieui committed
286 287 288 289
        if tab and tab.joined and config.get_by_tabname(
                'send_chat_states',
                self.general_jid,
        ) and not self.input.get_text() and self.on:
290 291 292
            self.send_chat_state('active')

    def on_info_win_size_changed(self):
mathieui's avatar
mathieui committed
293
        if self.core.information_win_size >= self.height - 3:
294
            return
mathieui's avatar
mathieui committed
295 296 297
        self.text_win.resize(
            self.height - 2 - self.core.information_win_size -
            Tab.tab_win_height(), self.width, 0, 0)
mathieui's avatar
mathieui committed
298 299 300
        self.info_header.resize(
            1, self.width, self.height - 2 - self.core.information_win_size -
            Tab.tab_win_height(), 0)
301 302 303 304

    def get_text_window(self):
        return self.text_win

305
    @refresh_wrapper.conditional
306
    def rename_user(self, old_nick, user):
307 308 309 310
        """
        The user changed her nick in the corresponding muc: update the tab’s name and
        display a message.
        """
mathieui's avatar
mathieui committed
311 312 313 314 315 316 317 318 319
        self.add_message(
            '\x19%(nick_col)s}%(old)s\x19%(info_col)s} is now '
            'known as \x19%(nick_col)s}%(new)s' % {
                'old': old_nick,
                'new': user.nick,
                'nick_col': dump_tuple(user.color),
                'info_col': dump_tuple(get_theme().COLOR_INFORMATION_TEXT)
            },
            typ=2)
320
        new_jid = self.jid.bare + '/' + user.nick
321
        self.name = new_jid
322
        return self.core.tabs.current_tab is self
323 324

    @refresh_wrapper.conditional
325
    def user_left(self, status_message, user):
326 327 328 329
        """
        The user left the associated MUC
        """
        self.deactivate()
330
        theme = get_theme()
mathieui's avatar
mathieui committed
331 332
        if config.get_by_tabname('display_user_color_in_join_part',
                                 self.general_jid):
333 334
            color = dump_tuple(user.color)
        else:
335
            color = dump_tuple(theme.COLOR_REMOTE_USER)
336

337
        if not status_message:
mathieui's avatar
mathieui committed
338 339 340 341
            self.add_message(
                '\x19%(quit_col)s}%(spec)s \x19%(nick_col)s}'
                '%(nick)s\x19%(info_col)s} has left the room' % {
                    'nick': user.nick,
342
                    'spec': theme.CHAR_QUIT,
mathieui's avatar
mathieui committed
343
                    'nick_col': color,
344 345
                    'quit_col': dump_tuple(theme.COLOR_QUIT_CHAR),
                    'info_col': dump_tuple(theme.COLOR_INFORMATION_TEXT)
mathieui's avatar
mathieui committed
346 347
                },
                typ=2)
348
        else:
mathieui's avatar
mathieui committed
349 350 351 352 353 354
            self.add_message(
                '\x19%(quit_col)s}%(spec)s \x19%(nick_col)s}'
                '%(nick)s\x19%(info_col)s} has left the room'
                ' (%(status)s)' % {
                    'status': status_message,
                    'nick': user.nick,
355
                    'spec': theme.CHAR_QUIT,
mathieui's avatar
mathieui committed
356
                    'nick_col': color,
357 358
                    'quit_col': dump_tuple(theme.COLOR_QUIT_CHAR),
                    'info_col': dump_tuple(theme.COLOR_INFORMATION_TEXT)
mathieui's avatar
mathieui committed
359 360
                },
                typ=2)
361
        return self.core.tabs.current_tab is self
362 363 364 365 366 367 368

    @refresh_wrapper.conditional
    def user_rejoined(self, nick):
        """
        The user (or at least someone with the same nick) came back in the MUC
        """
        self.activate()
369
        self.check_features()
370
        tab = self.parent_muc
371 372
        theme = get_theme()
        color = dump_tuple(theme.COLOR_REMOTE_USER)
373 374
        if tab and config.get_by_tabname('display_user_color_in_join_part',
                                         self.general_jid):
375 376 377
            user = tab.get_user_by_name(nick)
            if user:
                color = dump_tuple(user.color)
mathieui's avatar
mathieui committed
378 379 380 381 382
        self.add_message(
            '\x19%(join_col)s}%(spec)s \x19%(color)s}%(nick)s\x19'
            '%(info_col)s} joined the room' % {
                'nick': nick,
                'color': color,
383 384 385
                'spec': theme.CHAR_JOIN,
                'join_col': dump_tuple(theme.COLOR_JOIN_CHAR),
                'info_col': dump_tuple(theme.COLOR_INFORMATION_TEXT)
mathieui's avatar
mathieui committed
386 387
            },
            typ=2)
388
        return self.core.tabs.current_tab is self
389 390 391 392 393 394 395 396 397 398 399 400

    def activate(self, reason=None):
        self.on = True
        if reason:
            self.add_message(txt=reason, typ=2)

    def deactivate(self, reason=None):
        self.on = False
        if reason:
            self.add_message(txt=reason, typ=2)

    def matching_names(self):
401
        return [(3, self.jid.resource), (4, self.name)]
402

403
    def add_error(self, error_message):
404 405
        theme = get_theme()
        error = '\x19%s}%s\x19o' % (dump_tuple(theme.COLOR_CHAR_NACK),
406
                                    error_message)
mathieui's avatar
mathieui committed
407 408 409 410
        self.add_message(
            error,
            highlight=True,
            nickname='Error',
411
            nick_color=theme.COLOR_ERROR_MSG,
mathieui's avatar
mathieui committed
412
            typ=2)
413
        self.core.refresh_window()