""" Global commands which are to be linked to the Core class """ import asyncio from xml.etree import cElementTree as ET from typing import List, Optional, Tuple import logging from slixmpp import Iq, JID, InvalidJID from slixmpp.exceptions import XMPPError from slixmpp.xmlstream.xmlstream import NotConnectedError from slixmpp.xmlstream.stanzabase import StanzaBase from slixmpp.xmlstream.handler import Callback from slixmpp.xmlstream.matcher import StanzaPath from poezio import common from poezio import pep from poezio import tabs from poezio.bookmarks import Bookmark from poezio.common import safeJID from poezio.config import config, DEFAULT_CONFIG, options as config_opts from poezio import multiuserchat as muc from poezio.contact import Contact, Resource from poezio.plugin import PluginConfig from poezio.roster import roster from poezio.theming import dump_tuple, get_theme from poezio.decorators import command_args_parser from poezio.core.structs import Command, POSSIBLE_SHOW log = logging.getLogger(__name__) class CommandCore: def __init__(self, core): self.core = core @command_args_parser.quoted(0, 1) def help(self, args): """ /help [command_name] """ if not args: color = dump_tuple(get_theme().COLOR_HELP_COMMANDS) acc = [] buff = ['Global commands:'] for name, command in self.core.commands.items(): if isinstance(command, Command): acc.append(' \x19%s}%s\x19o - %s' % (color, name, command.short_desc)) else: acc.append(' \x19%s}%s\x19o' % (color, name)) acc = sorted(acc) buff.extend(acc) acc = [] buff.append('Tab-specific commands:') tab_commands = self.core.tabs.current_tab.commands for name, command in tab_commands.items(): if isinstance(command, Command): acc.append(' \x19%s}%s\x19o - %s' % (color, name, command.short_desc)) else: acc.append(' \x19%s}%s\x19o' % (color, name)) acc = sorted(acc) buff.extend(acc) msg = '\n'.join(buff) msg += "\nType /help to know what each command does" else: command = args[0].lstrip('/').strip() tab_commands = self.core.tabs.current_tab.commands if command in tab_commands: tup = tab_commands[command] elif command in self.core.commands: tup = self.core.commands[command] else: self.core.information('Unknown command: %s' % command, 'Error') return if isinstance(tup, Command): msg = 'Usage: /%s %s\n' % (command, tup.usage) msg += tup.desc else: msg = tup[1] self.core.information(msg, 'Help') @command_args_parser.quoted(1) def runkey(self, args): """ /runkey """ def replace_line_breaks(key): "replace ^J with \n" if key == '^J': return '\n' return key if args is None: return self.help('runkey') char = args[0] func = self.core.key_func.get(char, None) if func: func() else: res = self.core.do_command(replace_line_breaks(char), False) if res: self.core.refresh_window() @command_args_parser.quoted(1, 1, [None]) def status(self, args): """ /status [msg] """ if args is None: return self.help('status') if args[0] not in POSSIBLE_SHOW.keys(): return self.help('status') show = POSSIBLE_SHOW[args[0]] msg = args[1] pres = self.core.xmpp.make_presence() if msg: pres['status'] = msg pres['type'] = show self.core.events.trigger('send_normal_presence', pres) pres.send() current = self.core.tabs.current_tab is_muctab = isinstance(current, tabs.MucTab) if is_muctab and current.joined and show in ('away', 'xa'): current.send_chat_state('inactive') for tab in self.core.tabs: if isinstance(tab, tabs.MucTab) and tab.joined: muc.change_show(self.core.xmpp, tab.jid, tab.own_nick, show, msg) if hasattr(tab, 'directed_presence'): del tab.directed_presence self.core.set_status(show, msg) if is_muctab and current.joined and show not in ('away', 'xa'): current.send_chat_state('active') @command_args_parser.quoted(1, 2, [None, None]) def presence(self, args): """ /presence [type] [status] """ if args is None: return self.help('presence') jid, ptype, status = args[0], args[1], args[2] if jid == '.' and isinstance(self.core.tabs.current_tab, tabs.ChatTab): jid = self.core.tabs.current_tab.jid if ptype == 'available': ptype = None try: pres = self.core.xmpp.make_presence( pto=jid, ptype=ptype, pstatus=status) self.core.events.trigger('send_normal_presence', pres) pres.send() except (XMPPError, NotConnectedError): self.core.information('Could not send directed presence', 'Error') log.debug( 'Could not send directed presence to %s', jid, exc_info=True) return tab = self.core.tabs.by_name(jid) if tab: if ptype in ('xa', 'away'): tab.directed_presence = False chatstate = 'inactive' else: tab.directed_presence = True chatstate = 'active' if tab == self.core.tabs.current_tab: tab.send_chat_state(chatstate, True) if isinstance(tab, tabs.MucTab): for private in tab.privates: private.directed_presence = tab.directed_presence if self.core.tabs.current_tab in tab.privates: self.core.tabs.current_tab.send_chat_state(chatstate, True) @command_args_parser.quoted(1) def theme(self, args=None): """/theme """ if args is None: return self.help('theme') self.set('theme %s' % (args[0], )) @command_args_parser.quoted(1) def win(self, args): """ /win """ if args is None: return self.help('win') name = args[0] try: number = int(name) except ValueError: number = -1 name = name.lower() if number != -1 and self.core.tabs.current_tab == number: return prev_nb = self.core.previous_tab_nb self.core.previous_tab_nb = self.core.tabs.current_tab old_tab = self.core.tabs.current_tab if 0 <= number < len(self.core.tabs): if not self.core.tabs[number]: self.core.previous_tab_nb = prev_nb return self.core.tabs.set_current_index(number) else: match = self.core.tabs.find_match(name) if match is None: return self.core.tabs.set_current_tab(match) @command_args_parser.quoted(2) def move_tab(self, args): """ /move_tab old_pos new_pos """ if args is None: return self.help('move_tab') current_tab = self.core.tabs.current_tab if args[0] == '.': args[0] = current_tab.nb if args[1] == '.': args[1] = current_tab.nb def get_nb_from_value(value): "parse the cmdline to guess the tab the users wants" ref = None try: ref = int(value) except ValueError: old_tab = None for tab in self.core.tabs: if not old_tab and value == tab.name: old_tab = tab if not old_tab: self.core.information("Tab %s does not exist" % args[0], "Error") return None ref = old_tab.nb return ref old = get_nb_from_value(args[0]) new = get_nb_from_value(args[1]) if new is None or old is None: return self.core.information('Unable to move the tab.', 'Info') result = self.core.insert_tab(old, new) if not result: self.core.information('Unable to move the tab.', 'Info') self.core.refresh_window() @command_args_parser.quoted(0, 1) def list(self, args: List[str]) -> None: """ /list [server] Opens a MucListTab containing the list of the room in the specified server """ if args is None: return self.help('list') elif args: try: jid = JID(args[0]) except InvalidJID: return self.core.information('Invalid server %r' % jid, 'Error') else: if not isinstance(self.core.tabs.current_tab, tabs.MucTab): return self.core.information('Please provide a server', 'Error') jid = self.core.tabs.current_tab.jid if jid is None or not jid.domain: return None jid = JID(jid.domain) list_tab = tabs.MucListTab(self.core, jid) self.core.add_tab(list_tab, True) cb = list_tab.on_muc_list_item_received self.core.xmpp.plugin['xep_0030'].get_items(jid=jid, callback=cb) @command_args_parser.quoted(1) def version(self, args): """ /version """ if args is None: return self.help('version') jid = safeJID(args[0]) if jid.resource or jid not in roster or not roster[jid].resources: self.core.xmpp.plugin['xep_0092'].get_version( jid, callback=self.core.handler.on_version_result) elif jid in roster: for resource in roster[jid].resources: self.core.xmpp.plugin['xep_0092'].get_version( resource.jid, callback=self.core.handler.on_version_result) def _empty_join(self): tab = self.core.tabs.current_tab if not isinstance(tab, (tabs.MucTab, tabs.PrivateTab)): return (None, None) room = tab.jid.bare nick = tab.own_nick return (room, nick) def _parse_join_jid(self, jid_string: str) -> Tuple[Optional[str], Optional[str]]: # we try to join a server directly try: if jid_string.startswith('@'): server_root = True info = JID(jid_string[1:]) else: info = JID(jid_string) server_root = False except InvalidJID: return (None, None) set_nick = '' # type: Optional[str] if len(jid_string) > 1 and jid_string.startswith('/'): set_nick = jid_string[1:] elif info.resource: set_nick = info.resource # happens with /join /nickname, which is OK if info.bare == '': tab = self.core.tabs.current_tab if not isinstance(tab, tabs.MucTab): room, set_nick = (None, None) else: room = tab.jid.bare if not set_nick: set_nick = tab.own_nick else: room = info.bare # no server is provided, like "/join hello": # use the server of the current room if available # check if the current room's name has a server if room.find('@') == -1 and not server_root: tab = self.core.tabs.current_tab if isinstance(tab, tabs.MucTab) and tab.jid.domain: room += '@%s' % tab.jid.domain return (room, set_nick) @command_args_parser.quoted(0, 2) def join(self, args): """ /join [room][/nick] [password] """ if len(args) == 0: room, nick = self._empty_join() else: room, nick = self._parse_join_jid(args[0]) if not room and not nick: return # nothing was parsed room = room.lower() if nick == '': nick = self.core.own_nick # a password is provided if len(args) == 2: password = args[1] else: password = config.get_by_tabname('password', room, fallback=False) if room in self.core.pending_invites: del self.core.pending_invites[room] tab = self.core.tabs.by_name_and_class(room, tabs.MucTab) # New tab if tab is None: tab = self.core.open_new_room(room, nick, password=password) tab.join() else: self.core.focus_tab(tab) if tab.own_nick == nick and tab.joined: self.core.information('/join: Nothing to do.', 'Info') else: tab.command_part('') tab.own_nick = nick tab.password = password tab.join() if config.get('bookmark_on_join'): method = 'remote' if config.get( 'use_remote_bookmarks') else 'local' self._add_bookmark('%s/%s' % (room, nick), True, password, method) if tab == self.core.tabs.current_tab: tab.refresh() self.core.doupdate() @command_args_parser.quoted(0, 2) def bookmark_local(self, args): """ /bookmark_local [room][/nick] [password] """ if not args and not isinstance(self.core.tabs.current_tab, tabs.MucTab): return password = args[1] if len(args) > 1 else None jid = args[0] if args else None self._add_bookmark(jid, True, password, 'local') @command_args_parser.quoted(0, 3) def bookmark(self, args): """ /bookmark [room][/nick] [autojoin] [password] """ if not args and not isinstance(self.core.tabs.current_tab, tabs.MucTab): return jid = args[0] if args else '' password = args[2] if len(args) > 2 else None if not config.get('use_remote_bookmarks'): return self._add_bookmark(jid, True, password, 'local') if len(args) > 1: autojoin = False if args[1].lower() != 'true' else True else: autojoin = True self._add_bookmark(jid, autojoin, password, 'remote') def _add_bookmark(self, jid, autojoin, password, method): nick = None if not jid: tab = self.core.tabs.current_tab roomname = tab.jid.bare if tab.joined and tab.own_nick != self.core.own_nick: nick = tab.own_nick if password is None and tab.password is not None: password = tab.password elif jid == '*': return self._add_wildcard_bookmarks(method) else: info = safeJID(jid) roomname, nick = info.bare, info.resource if roomname == '': tab = self.core.tabs.current_tab if not isinstance(tab, tabs.MucTab): return roomname = tab.jid.bare bookmark = self.core.bookmarks[roomname] if bookmark is None: bookmark = Bookmark(roomname) self.core.bookmarks.append(bookmark) bookmark.method = method bookmark.autojoin = autojoin if nick: bookmark.nick = nick if password: bookmark.password = password self.core.bookmarks.save_local() self.core.bookmarks.save_remote(self.core.xmpp, self.core.handler.on_bookmark_result) def _add_wildcard_bookmarks(self, method): new_bookmarks = [] for tab in self.core.get_tabs(tabs.MucTab): bookmark = self.core.bookmarks[tab.jid.bare] if not bookmark: bookmark = Bookmark(tab.jid.bare, autojoin=True, method=method) new_bookmarks.append(bookmark) else: bookmark.method = method new_bookmarks.append(bookmark) self.core.bookmarks.remove(bookmark) new_bookmarks.extend(self.core.bookmarks.bookmarks) self.core.bookmarks.set(new_bookmarks) self.core.bookmarks.save_local() self.core.bookmarks.save_remote(self.core.xmpp, self.core.handler.on_bookmark_result) @command_args_parser.ignored def bookmarks(self): """/bookmarks""" tab = self.core.tabs.by_name_and_class('Bookmarks', tabs.BookmarksTab) old_tab = self.core.tabs.current_tab if tab: self.core.tabs.set_current_tab(tab) else: tab = tabs.BookmarksTab(self.core, self.core.bookmarks) self.core.tabs.append(tab) self.core.tabs.set_current_tab(tab) @command_args_parser.quoted(0, 1) def remove_bookmark(self, args): """/remove_bookmark [jid]""" def cb(success): if success: self.core.information('Bookmark deleted', 'Info') else: self.core.information('Error while deleting the bookmark', 'Error') if not args: tab = self.core.tabs.current_tab if isinstance(tab, tabs.MucTab) and self.core.bookmarks[tab.jid.bare]: self.core.bookmarks.remove(tab.jid.bare) self.core.bookmarks.save(self.core.xmpp, callback=cb) else: self.core.information('No bookmark to remove', 'Info') else: if self.core.bookmarks[args[0]]: self.core.bookmarks.remove(args[0]) self.core.bookmarks.save(self.core.xmpp, callback=cb) else: self.core.information('No bookmark to remove', 'Info') @command_args_parser.quoted(0, 1) def command_accept(self, args): """ Accept a JID. Authorize it AND subscribe to it """ if not args: tab = self.core.tabs.current_tab RosterInfoTab = tabs.RosterInfoTab if not isinstance(tab, RosterInfoTab): return self.core.information('No JID specified', 'Error') else: item = tab.selected_row if isinstance(item, Contact): jid = item.bare_jid else: return self.core.information('No subscription to accept', 'Warning') else: jid = safeJID(args[0]).bare nodepart = safeJID(jid).user jid = safeJID(jid) # crappy transports putting resources inside the node part if '\\2f' in nodepart: jid.user = nodepart.split('\\2f')[0] contact = roster[jid] if contact is None: return self.core.information('No subscription to accept', 'Warning') contact.pending_in = False roster.modified() self.core.xmpp.send_presence(pto=jid, ptype='subscribed') self.core.xmpp.client_roster.send_last_presence() if contact.subscription in ('from', 'none') and not contact.pending_out: self.core.xmpp.send_presence( pto=jid, ptype='subscribe', pnick=self.core.own_nick) self.core.information('%s is now authorized' % jid, 'Roster') @command_args_parser.quoted(1) def command_add(self, args): """ Add the specified JID to the roster, and automatically accept the reverse subscription """ if args is None: tab = self.core.tabs.current_tab ConversationTab = tabs.ConversationTab if isinstance(tab, ConversationTab): jid = tab.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() return self.core.information('%s was added to the roster' % jid, 'Roster') else: return self.core.information('No JID specified', 'Error') jid = safeJID(safeJID(args[0]).bare) if not str(jid): self.core.information( 'The provided JID (%s) is not valid' % (args[0], ), 'Error') return 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') @command_args_parser.ignored def command_reconnect(self): """ /reconnect """ if self.core.xmpp.is_connected(): self.core.disconnect(reconnect=True) else: self.core.xmpp.start() @command_args_parser.quoted(0, 3) def set(self, args): """ /set [module|][section]