conversationtab.py 17.6 KB
Newer Older
1 2 3 4 5 6
"""
Module for the ConversationTabs

A ConversationTab is a direct chat between two JIDs, outside of a room.

There are two different instances of a ConversationTab:
7 8 9
- A DynamicConversationTab that used to implement XEP-0296 (best
    practices for resource locking), which now stays on the bare JID at
    any time. This is the default.
10 11 12 13
- A StaticConversationTab that will stay focused on one resource all
    the time.

"""
14
import curses
15 16
import logging
from typing import Dict, Callable
17

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

20 21 22 23 24
from poezio import common
from poezio import windows
from poezio import xhtml
from poezio.common import safeJID
from poezio.config import config
25
from poezio.core.structs import Command
26 27
from poezio.decorators import refresh_wrapper
from poezio.roster import roster
28
from poezio.text_buffer import CorrectionError
29 30
from poezio.theming import get_theme, dump_tuple
from poezio.decorators import command_args_parser
31

32 33
log = logging.getLogger(__name__)

mathieui's avatar
mathieui committed
34

35
class ConversationTab(OneToOneTab):
36 37 38 39
    """
    The tab containg a normal conversation (not from a MUC)
    Must not be instantiated, use Static or Dynamic version only.
    """
40 41 42
    plugin_commands = {}  # type: Dict[str, Command]
    plugin_keys = {}  # type: Dict[str, Callable]
    additional_information = {}  # type: Dict[str, Callable[[str], str]]
43
    message_type = 'chat'
mathieui's avatar
mathieui committed
44

45 46
    def __init__(self, core, jid):
        OneToOneTab.__init__(self, core, jid)
47 48 49
        self.nick = None
        self.nick_sent = False
        self.state = 'normal'
mathieui's avatar
mathieui committed
50
        self.name = jid  # a conversation tab is linked to one specific full jid OR bare jid
51 52 53 54 55 56 57
        self.text_win = windows.TextWin()
        self._text_buffer.add_window(self.text_win)
        self.upper_bar = windows.ConversationStatusMessageWin()
        self.input = windows.MessageInput()
        # keys
        self.key_func['^I'] = self.completion
        # commands
mathieui's avatar
mathieui committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
        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 the user.')
        self.register_command(
            'info',
            self.command_info,
            shortdesc='Get the status of the contact.')
        self.register_command(
            'last_activity',
            self.command_last_activity,
            usage='[jid]',
            desc='Get the last activity of the given or the current contact.',
            shortdesc='Get the activity.',
            completion=self.core.completion.last_activity)
        self.register_command(
            'add',
            self.command_add,
            desc='Add the current JID to your roster, ask them to'
            ' allow you to see his presence, and allow them to'
            ' see your presence.',
            shortdesc='Add a user to your roster.')
82 83 84 85 86 87
        self.register_command(
            'invite',
            self.core.command.impromptu,
            desc='Invite people into an impromptu room.',
            shortdesc='Invite other users to the discussion',
            completion=self.core.completion.impromptu)
88 89 90 91 92
        self.update_commands()
        self.update_keys()

    @property
    def general_jid(self):
93
        return safeJID(self.name).bare
94

mathieui's avatar
mathieui committed
95 96 97
    def get_info_header(self):
        raise NotImplementedError

98 99 100 101 102
    @staticmethod
    def add_information_element(plugin_name, callback):
        """
        Lets a plugin add its own information to the ConversationInfoWin
        """
103
        ConversationTab.additional_information[plugin_name] = callback
104 105 106

    @staticmethod
    def remove_information_element(plugin_name):
107
        del ConversationTab.additional_information[plugin_name]
108 109 110 111

    def completion(self):
        self.complete_commands(self.input)

112
    @command_args_parser.raw
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    def command_say(self, line, attention=False, correct=False):
        msg = self.core.xmpp.make_message(self.get_dest_jid())
        msg['type'] = 'chat'
        msg['body'] = line
        if not self.nick_sent:
            msg['nick'] = self.core.own_nick
            self.nick_sent = True
        # trigger the event BEFORE looking for colors.
        # and before displaying the message in the window
        # This lets a plugin insert \x19xxx} colors, that will
        # be converted in xhtml.
        self.core.events.trigger('conversation_say', msg, self)
        if not msg['body']:
            self.cancel_paused_delay()
            self.text_win.refresh()
            self.input.refresh()
            return
        replaced = False
        if correct or msg['replace']['id']:
            msg['replace']['id'] = self.last_sent_message['id']
133
            if config.get_by_tabname('group_corrections', self.name):
134
                try:
mathieui's avatar
mathieui committed
135 136 137 138 139 140
                    self.modify_message(
                        msg['body'],
                        self.last_sent_message['id'],
                        msg['id'],
                        jid=self.core.xmpp.boundjid,
                        nickname=self.core.own_nick)
141
                    replaced = True
142
                except CorrectionError:
143 144 145 146 147 148 149
                    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'])
150
        if config.get_by_tabname('send_chat_states', self.general_jid):
151 152
            needed = 'inactive' if self.inactive else 'active'
            msg['chat_state'] = needed
153
        if attention:
154 155 156 157 158 159 160 161
            msg['attention'] = True
        self.core.events.trigger('conversation_say_after', msg, self)
        if not msg['body']:
            self.cancel_paused_delay()
            self.text_win.refresh()
            self.input.refresh()
            return
        if not replaced:
mathieui's avatar
mathieui committed
162 163 164 165 166 167 168
            self.add_message(
                msg['body'],
                nickname=self.core.own_nick,
                nick_color=get_theme().COLOR_OWN_NICK,
                identifier=msg['id'],
                jid=self.core.xmpp.boundjid,
                typ=1)
169 170

        self.last_sent_message = msg
171
        msg._add_receipt = True
172 173 174 175 176
        msg.send()
        self.cancel_paused_delay()
        self.text_win.refresh()
        self.input.refresh()

177 178
    @command_args_parser.quoted(0, 1)
    def command_last_activity(self, args):
179
        """
mathieui's avatar
mathieui committed
180
        /last_activity [jid]
181
        """
mathieui's avatar
mathieui committed
182
        if args and args[0]:
183
            return self.core.command.last_activity(args[0])
184 185 186 187

        def callback(iq):
            if iq['type'] != 'result':
                if iq['error']['type'] == 'auth':
mathieui's avatar
mathieui committed
188 189 190
                    self.core.information(
                        'You are not allowed to see the activity of this contact.',
                        'Error')
191
                else:
mathieui's avatar
mathieui committed
192 193
                    self.core.information('Error retrieving the activity',
                                          'Error')
194 195 196 197 198 199 200
                return
            seconds = iq['last_activity']['seconds']
            status = iq['last_activity']['status']
            from_ = iq['from']
            msg = '\x19%s}The last activity of %s was %s ago%s'
            if not safeJID(from_).user:
                msg = '\x19%s}The uptime of %s is %s.' % (
mathieui's avatar
mathieui committed
201 202
                    dump_tuple(get_theme().COLOR_INFORMATION_TEXT), from_,
                    common.parse_secs_to_str(seconds))
203 204 205 206 207
            else:
                msg = '\x19%s}The last activity of %s was %s ago%s' % (
                    dump_tuple(get_theme().COLOR_INFORMATION_TEXT),
                    from_,
                    common.parse_secs_to_str(seconds),
mathieui's avatar
mathieui committed
208 209 210
                    (' and his/her last status was %s' % status)
                    if status else '',
                )
211 212 213
            self.add_message(msg)
            self.core.refresh_window()

mathieui's avatar
mathieui committed
214 215
        self.core.xmpp.plugin['xep_0012'].get_last_activity(
            self.get_dest_jid(), callback=callback)
216 217

    @refresh_wrapper.conditional
218 219
    @command_args_parser.ignored
    def command_info(self):
220 221 222 223 224 225 226 227 228 229
        contact = roster[self.get_dest_jid()]
        jid = safeJID(self.get_dest_jid())
        if contact:
            if jid.resource:
                resource = contact[jid.full]
            else:
                resource = contact.get_highest_priority_resource()
        else:
            resource = None
        if resource:
mathieui's avatar
mathieui committed
230 231 232 233 234 235 236 237
            status = (
                'Status: %s' % resource.status) if resource.status else ''
            self._text_buffer.add_message(
                "\x19%(info_col)s}Show: %(show)s, %(status)s\x19o" % {
                    'show': resource.presence or 'available',
                    'status': status,
                    'info_col': dump_tuple(get_theme().COLOR_INFORMATION_TEXT)
                })
238 239
            return True
        else:
mathieui's avatar
mathieui committed
240
            self._text_buffer.add_message(
mathieui's avatar
mathieui committed
241 242
                "\x19%(info_col)s}No information available\x19o" %
                {'info_col': dump_tuple(get_theme().COLOR_INFORMATION_TEXT)})
243 244
            return True

245 246
    @command_args_parser.quoted(0, 1)
    def command_version(self, args):
247
        """
248
        /version [jid]
249
        """
250
        if args:
251
            return self.core.command.version(args[0])
252 253 254 255 256
        jid = safeJID(self.name)
        if not jid.resource:
            if jid in roster:
                resource = roster[jid].get_highest_priority_resource()
                jid = resource.jid if resource else jid
257 258
        self.core.xmpp.plugin['xep_0092'].get_version(
            jid, callback=self.core.handler.on_version_result)
259

Link Mauve's avatar
Link Mauve committed
260 261 262 263 264 265 266 267 268 269 270 271 272
    @command_args_parser.ignored
    def command_add(self):
        """
        Add the current JID to the roster, and automatically
        accept the reverse subscription
        """
        jid = self.general_jid
        if jid in roster and roster[jid].subscription in ('to', 'both'):
            return self.core.information('Already subscribed.', 'Roster')
        roster.add(jid)
        roster.modified()
        self.core.information('%s was added to the roster' % jid, 'Roster')

273
    def resize(self):
274
        self.need_resize = False
275 276 277 278 279 280 281 282 283 284 285
        if self.size.tab_degrade_y:
            display_bar = False
            info_win_height = 0
            tab_win_height = 0
            bar_height = 0
        else:
            display_bar = True
            info_win_height = self.core.information_win_size
            tab_win_height = Tab.tab_win_height()
            bar_height = 1

mathieui's avatar
mathieui committed
286 287 288
        self.text_win.resize(
            self.height - 2 - bar_height - info_win_height - tab_win_height,
            self.width, bar_height, 0)
289
        self.text_win.rebuild_everything(self._text_buffer)
290 291
        if display_bar:
            self.upper_bar.resize(1, self.width, 0, 0)
mathieui's avatar
mathieui committed
292 293 294
        self.get_info_header().resize(
            1, self.width, self.height - 2 - info_win_height - tab_win_height,
            0)
295
        self.input.resize(1, self.width, self.height - 1, 0)
296 297 298 299

    def refresh(self):
        if self.need_resize:
            self.resize()
300
        log.debug('  TAB   Refresh: %s', self.__class__.__name__)
301 302
        display_bar = display_info_win = not self.size.tab_degrade_y

303
        self.text_win.refresh()
304 305

        if display_bar:
mathieui's avatar
mathieui committed
306 307 308 309 310
            self.upper_bar.refresh(self.get_dest_jid(),
                                   roster[self.get_dest_jid()])
        self.get_info_header().refresh(
            self.get_dest_jid(), roster[self.get_dest_jid()], self.text_win,
            self.chatstate, ConversationTab.additional_information)
311 312 313

        if display_info_win:
            self.info_win.refresh()
314 315 316 317
        self.refresh_tab_win()
        self.input.refresh()

    def refresh_info_header(self):
mathieui's avatar
mathieui committed
318 319 320
        self.get_info_header().refresh(
            self.get_dest_jid(), roster[self.get_dest_jid()], self.text_win,
            self.chatstate, ConversationTab.additional_information)
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
        self.input.refresh()

    def get_nick(self):
        jid = safeJID(self.name)
        contact = roster[jid.bare]
        if contact:
            return contact.name or jid.user
        else:
            if self.nick:
                return self.nick
            return jid.user

    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)
mathieui's avatar
mathieui committed
338 339 340
        empty_after = self.input.get_text() == '' or (
            self.input.get_text().startswith('/')
            and not self.input.get_text().startswith('//'))
341 342 343 344 345 346 347 348 349 350 351 352 353
        self.send_composing_chat_state(empty_after)
        return False

    def on_lose_focus(self):
        contact = roster[self.get_dest_jid()]
        jid = safeJID(self.get_dest_jid())
        if contact:
            if jid.resource:
                resource = contact[jid.full]
            else:
                resource = contact.get_highest_priority_resource()
        else:
            resource = None
354 355 356 357
        if self.input.text:
            self.state = 'nonempty'
        else:
            self.state = 'normal'
358 359
        self.text_win.remove_line_separator()
        self.text_win.add_line_separator(self._text_buffer)
360
        if config.get_by_tabname('send_chat_states', self.general_jid):
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
            if resource:
                self.send_chat_state('inactive')
        self.check_scrolled()

    def on_gain_focus(self):
        contact = roster[self.get_dest_jid()]
        jid = safeJID(self.get_dest_jid())
        if contact:
            if jid.resource:
                resource = contact[jid.full]
            else:
                resource = contact.get_highest_priority_resource()
        else:
            resource = None

        self.state = 'current'
        curses.curs_set(1)
378 379
        if (config.get_by_tabname('send_chat_states', self.general_jid)
                and (not self.input.get_text()
mathieui's avatar
mathieui committed
380
                     or not self.input.get_text().startswith('//'))):
381 382 383 384
            if resource:
                self.send_chat_state('active')

    def on_info_win_size_changed(self):
mathieui's avatar
mathieui committed
385
        if self.core.information_win_size >= self.height - 3:
386
            return
mathieui's avatar
mathieui committed
387 388 389
        self.text_win.resize(
            self.height - 3 - self.core.information_win_size -
            Tab.tab_win_height(), self.width, 1, 0)
mathieui's avatar
mathieui committed
390 391 392
        self.get_info_header().resize(
            1, self.width, self.height - 2 - self.core.information_win_size -
            Tab.tab_win_height(), 0)
393 394 395 396 397 398

    def get_text_window(self):
        return self.text_win

    def on_close(self):
        Tab.on_close(self)
399
        if config.get_by_tabname('send_chat_states', self.general_jid):
400 401 402 403
            self.send_chat_state('gone')

    def matching_names(self):
        res = []
404
        jid = safeJID(self.name)
405 406
        res.append((2, jid.bare))
        res.append((1, jid.user))
407
        contact = roster[self.name]
408 409 410 411
        if contact and contact.name:
            res.append((0, contact.name))
        return res

mathieui's avatar
mathieui committed
412

413 414
class DynamicConversationTab(ConversationTab):
    """
415 416 417
    A conversation tab associated with one bare JID.  It used to
    support resource locking (as described in XEP-0296), but that was a
    bad idea so it has been removed.
418 419
    Only one DynamicConversationTab can be opened for a given jid.
    """
420 421
    plugin_commands = {}  # type: Dict[str, Command]
    plugin_keys = {}  # type: Dict[str, Callable]
mathieui's avatar
mathieui committed
422

mathieui's avatar
mathieui committed
423
    def __init__(self, core, jid, resource=None):
424 425
        self.locked_resource = None
        self.name = safeJID(jid).bare
mathieui's avatar
mathieui committed
426
        ConversationTab.__init__(self, core, jid)
mathieui's avatar
mathieui committed
427
        self.info_header = windows.DynamicConversationInfoWin()
mathieui's avatar
mathieui committed
428
        self.register_command(
mathieui's avatar
mathieui committed
429
            'unlock', self.unlock_command, shortdesc='Deprecated, do nothing.')
mathieui's avatar
mathieui committed
430
        self.resize()
mathieui's avatar
mathieui committed
431 432
        self.update_commands()
        self.update_keys()
mathieui's avatar
mathieui committed
433 434 435

    def get_info_header(self):
        return self.info_header
436 437

    def lock(self, resource):
438
        pass
439 440

    def unlock_command(self, arg=None):
441
        pass
442

mathieui's avatar
mathieui committed
443
    def unlock(self, from_=None):
444
        pass
445 446 447

    def get_dest_jid(self):
        """
448
        Returns the bare jid.
449
        """
450
        return self.name
451 452 453 454 455 456 457

    def refresh(self):
        """
        Different from the parent class only for the info_header object.
        """
        if self.need_resize:
            self.resize()
458
        log.debug('  TAB   Refresh: %s', self.__class__.__name__)
459 460
        display_bar = display_info_win = not self.size.tab_degrade_y

461
        self.text_win.refresh()
462
        if display_bar:
463
            self.upper_bar.refresh(self.name, roster[self.name])
464
        displayed_jid = self.name
465
        self.get_info_header().refresh(displayed_jid, roster[self.name],
mathieui's avatar
mathieui committed
466 467
                                       self.text_win, self.chatstate,
                                       ConversationTab.additional_information)
468 469 470
        if display_info_win:
            self.info_win.refresh()

471 472 473 474 475 476 477
        self.refresh_tab_win()
        self.input.refresh()

    def refresh_info_header(self):
        """
        Different from the parent class only for the info_header object.
        """
478
        displayed_jid = self.name
479
        self.get_info_header().refresh(displayed_jid, roster[self.name],
mathieui's avatar
mathieui committed
480 481
                                       self.text_win, self.chatstate,
                                       ConversationTab.additional_information)
482 483
        self.input.refresh()

mathieui's avatar
mathieui committed
484

485 486 487 488 489
class StaticConversationTab(ConversationTab):
    """
    A conversation tab associated with one Full JID. It cannot be locked to
    an different resource or unlocked.
    """
490 491
    plugin_commands = {}  # type: Dict[str, Command]
    plugin_keys = {}  # type: Dict[str, Callable]
mathieui's avatar
mathieui committed
492

mathieui's avatar
mathieui committed
493
    def __init__(self, core, jid):
mathieui's avatar
mathieui committed
494
        assert (safeJID(jid).resource)
mathieui's avatar
mathieui committed
495
        ConversationTab.__init__(self, core, jid)
mathieui's avatar
mathieui committed
496 497
        self.info_header = windows.ConversationInfoWin()
        self.resize()
mathieui's avatar
mathieui committed
498 499
        self.update_commands()
        self.update_keys()
500

mathieui's avatar
mathieui committed
501 502
    def get_info_header(self):
        return self.info_header