privatetab.py 15.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 14 15 16 17
import logging
log = logging.getLogger(__name__)

import curses

mathieui's avatar
mathieui committed
18
from poezio.tabs import OneToOneTab, MucTab, Tab
19

20 21 22 23 24 25 26 27 28
from poezio import fixes
from poezio import windows
from poezio import xhtml
from poezio.common import safeJID
from poezio.config import config
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
29

30
class PrivateTab(OneToOneTab):
31 32 33 34 35
    """
    The tab containg a private conversation (someone from a MUC)
    """
    message_type = 'chat'
    plugin_commands = {}
36
    additional_information = {}
37
    plugin_keys = {}
38 39
    def __init__(self, core, name, nick):
        OneToOneTab.__init__(self, core, name)
40 41 42 43 44 45 46 47 48 49
        self.own_nick = nick
        self.name = name
        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
        self.register_command('info', self.command_info,
50 51
                desc='Display some information about the user in the MUC: its/his/her role, affiliation, status and status message.',
                shortdesc='Info about the user.')
52
        self.register_command('version', self.command_version,
53 54
                desc='Get the software version of the current interlocutor (usually its XMPP client and Operating System).',
                shortdesc='Get the software version of a jid.')
55 56 57 58 59 60
        self.resize()
        self.parent_muc = self.core.get_tab_by_name(safeJID(name).bare, MucTab)
        self.on = True
        self.update_commands()
        self.update_keys()

61 62 63 64 65 66
    def remote_user_color(self):
        user = self.parent_muc.get_user_by_name(safeJID(self.name).resource)
        if user:
            return dump_tuple(user.color);
        return super().remote_user_color()

67 68
    @property
    def general_jid(self):
69
        return self.name
70

71 72 73
    def get_dest_jid(self):
        return self.name

74 75 76 77 78 79 80 81 82
    @property
    def nick(self):
        return self.get_nick()

    @staticmethod
    def add_information_element(plugin_name, callback):
        """
        Lets a plugin add its own information to the PrivateInfoWin
        """
83
        PrivateTab.additional_information[plugin_name] = callback
84 85 86

    @staticmethod
    def remove_information_element(plugin_name):
87
        del PrivateTab.additional_information[plugin_name]
88 89

    def load_logs(self, log_nb):
90
        logs = logger.get_logs(safeJID(self.name).full.replace('/', '\\'), log_nb)
91
        return logs
92 93 94 95 96 97

    def log_message(self, txt, nickname, time=None, typ=1):
        """
        Log the messages in the archives.
        """
        if not logger.log_message(self.name, nickname, txt, date=time, typ=typ):
98
            self.core.information('Unable to write in the log file', 'Error')
99 100

    def on_close(self):
101
        super().on_close()
102 103 104 105 106 107 108 109 110 111 112 113 114
        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]
115
        after = config.get('after_completion') + ' '
116 117 118 119 120 121 122 123 124 125
        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)
        empty_after = self.input.get_text() == '' or (self.input.get_text().startswith('/') and not self.input.get_text().startswith('//'))
        self.send_composing_chat_state(empty_after)

126
    @command_args_parser.raw
127 128 129
    def command_say(self, line, attention=False, correct=False):
        if not self.on:
            return
130
        msg = self.core.xmpp.make_message(self.name)
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
        msg['type'] = 'chat'
        msg['body'] = line
        # 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']:
            self.cancel_paused_delay()
            self.text_win.refresh()
            self.input.refresh()
            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']
146
            if config.get_by_tabname('group_corrections', self.name):
147 148 149 150 151 152 153 154 155 156 157 158 159
                try:
                    self.modify_message(msg['body'], self.last_sent_message['id'], msg['id'],
                            user=user, jid=self.core.xmpp.boundjid, nickname=self.own_nick)
                    replaced = True
                except:
                    log.error('Unable to correct a message', exc_info=True)
        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'])
160 161
        if (config.get_by_tabname('send_chat_states', self.general_jid) and
                self.remote_wants_chatstates is not False):
162 163 164 165 166 167 168 169 170 171 172 173
            needed = 'inactive' if self.inactive else 'active'
            msg['chat_state'] = needed
        if attention and self.remote_supports_attention:
            msg['attention'] = True
        self.core.events.trigger('private_say_after', msg, self)
        if not msg['body']:
            self.cancel_paused_delay()
            self.text_win.refresh()
            self.input.refresh()
            return
        if not replaced:
            self.add_message(msg['body'],
174
                    nickname=self.own_nick or self.core.own_nick,
175 176 177 178 179 180 181
                    forced_user=user,
                    nick_color=get_theme().COLOR_OWN_NICK,
                    identifier=msg['id'],
                    jid=self.core.xmpp.boundjid,
                    typ=1)

        self.last_sent_message = msg
182 183
        if self.remote_supports_receipts:
            msg._add_receipt = True
184 185 186 187 188
        msg.send()
        self.cancel_paused_delay()
        self.text_win.refresh()
        self.input.refresh()

189 190
    @command_args_parser.quoted(0, 1)
    def command_version(self, args):
191 192 193 194 195 196 197
        """
        /version
        """
        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,
198 199 200
                                                             res.get('name') or 'an unknown software',
                                                             res.get('version') or 'unknown',
                                                             res.get('os') or 'an unknown platform')
201
            self.core.information(version, 'Info')
202
        if args:
203
            return self.core.command.version(args[0])
204
        jid = safeJID(self.name)
205 206
        fixes.get_version(self.core.xmpp, jid,
                callback=callback)
207

208
    @command_args_parser.quoted(0, 1)
209 210 211 212
    def command_info(self, arg):
        """
        /info
        """
mathieui's avatar
mathieui committed
213 214
        if arg and arg[0]:
            self.parent_muc.command_info(arg[0])
215 216 217 218 219
        else:
            user = safeJID(self.name).resource
            self.parent_muc.command_info(user)

    def resize(self):
220 221
        self.need_resize = False

222 223 224 225 226 227 228 229 230
        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()

        self.text_win.resize(self.height - 2 - info_win_height - tab_win_height,
                             self.width, 0, 0)
231
        self.text_win.rebuild_everything(self._text_buffer)
232 233 234 235
        self.info_header.resize(1, self.width,
                                self.height - 2 - info_win_height
                                    - tab_win_height,
                                0)
236 237 238 239 240
        self.input.resize(1, self.width, self.height-1, 0)

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

244
        self.text_win.refresh()
245
        self.info_header.refresh(self.name, self.text_win, self.chatstate,
246
                                 PrivateTab.additional_information)
247 248 249
        if display_info_win:
            self.info_win.refresh()

250 251 252 253
        self.refresh_tab_win()
        self.input.refresh()

    def refresh_info_header(self):
254
        self.info_header.refresh(self.name, self.text_win, self.chatstate, PrivateTab.additional_information)
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
        self.input.refresh()

    def get_nick(self):
        return safeJID(self.name).resource

    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
        empty_after = self.input.get_text() == '' or (self.input.get_text().startswith('/') and not self.input.get_text().startswith('//'))
        tab = self.core.get_tab_by_name(safeJID(self.name).bare, MucTab)
        if tab and tab.joined:
            self.send_composing_chat_state(empty_after)
        return False

    def on_lose_focus(self):
274 275 276 277 278
        if self.input.text:
            self.state = 'nonempty'
        else:
            self.state = 'normal'

279 280 281
        self.text_win.remove_line_separator()
        self.text_win.add_line_separator(self._text_buffer)
        tab = self.core.get_tab_by_name(safeJID(self.name).bare, MucTab)
282
        if tab and tab.joined and config.get_by_tabname('send_chat_states',
283
                self.general_jid) and self.on:
284 285 286 287 288 289 290
            self.send_chat_state('inactive')
        self.check_scrolled()

    def on_gain_focus(self):
        self.state = 'current'
        curses.curs_set(1)
        tab = self.core.get_tab_by_name(safeJID(self.name).bare, MucTab)
291 292
        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:
293 294 295 296 297 298 299 300 301 302 303
            self.send_chat_state('active')

    def on_info_win_size_changed(self):
        if self.core.information_win_size >= self.height-3:
            return
        self.text_win.resize(self.height-2-self.core.information_win_size - Tab.tab_win_height(), self.width, 0, 0)
        self.info_header.resize(1, self.width, self.height-2-self.core.information_win_size - Tab.tab_win_height(), 0)

    def get_text_window(self):
        return self.text_win

304
    @refresh_wrapper.conditional
305
    def rename_user(self, old_nick, user):
306 307 308 309
        """
        The user changed her nick in the corresponding muc: update the tab’s name and
        display a message.
        """
310 311 312 313 314 315 316
        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)
        new_jid = safeJID(self.name).bare+'/'+user.nick
317
        self.name = new_jid
318
        return self.core.current_tab() is self
319 320

    @refresh_wrapper.conditional
321
    def user_left(self, status_message, user):
322 323 324 325
        """
        The user left the associated MUC
        """
        self.deactivate()
326 327 328 329 330
        if config.get_by_tabname('display_user_color_in_join_part', self.general_jid):
            color = dump_tuple(user.color)
        else:
            color = dump_tuple(get_theme().COLOR_REMOTE_USER)

331
        if not status_message:
332
            self.add_message('\x19%(quit_col)s}%(spec)s \x19%(nick_col)s}'
333 334 335
                             '%(nick)s\x19%(info_col)s} has left the room' % {
                                 'nick': user.nick, 'spec': get_theme().CHAR_QUIT,
                                 'nick_col': color,
336
                                 'quit_col': dump_tuple(get_theme().COLOR_QUIT_CHAR),
337 338
                                 'info_col': dump_tuple(get_theme().COLOR_INFORMATION_TEXT)},
                             typ=2)
339
        else:
340
            self.add_message('\x19%(quit_col)s}%(spec)s \x19%(nick_col)s}'
341 342 343 344
                             '%(nick)s\x19%(info_col)s} has left the room'
                             ' (%(status)s)' % { 'status': status_message,
                                 'nick': user.nick, 'spec': get_theme().CHAR_QUIT,
                                 'nick_col': color,
345
                                 'quit_col': dump_tuple(get_theme().COLOR_QUIT_CHAR),
346 347
                                 'info_col': dump_tuple(get_theme().COLOR_INFORMATION_TEXT)},
                             typ=2)
348 349 350 351 352 353 354 355
        return self.core.current_tab() is self

    @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()
356
        self.check_features()
357 358
        tab = self.parent_muc
        color = dump_tuple(get_theme().COLOR_REMOTE_USER)
359 360
        if tab and config.get_by_tabname('display_user_color_in_join_part',
                                         self.general_jid):
361 362 363
            user = tab.get_user_by_name(nick)
            if user:
                color = dump_tuple(user.color)
364 365 366 367 368 369
        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, 'spec':get_theme().CHAR_JOIN,
                             'join_col': dump_tuple(get_theme().COLOR_JOIN_CHAR),
                             'info_col': dump_tuple(get_theme().COLOR_INFORMATION_TEXT)},
                         typ=2)
370 371 372 373 374 375 376 377 378
        return self.core.current_tab() is self

    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
379
        self.remote_wants_chatstates = None
380 381 382 383
        if reason:
            self.add_message(txt=reason, typ=2)

    def matching_names(self):
384
        return [(3, safeJID(self.name).resource), (4, self.name)]
385

386 387 388 389 390 391
    def add_error(self, error_message):
        error = '\x19%s}%s\x19o' % (dump_tuple(get_theme().COLOR_CHAR_NACK),
                                    error_message)
        self.add_message(error, highlight=True, nickname='Error',
                         nick_color=get_theme().COLOR_ERROR_MSG, typ=2)
        self.core.refresh_window()
392