Commit 7a485ef4 authored by mathieui's avatar mathieui

Add a common.safeJID function, and use it everywhere

parent a14141bc
......@@ -3,7 +3,7 @@ import logging
from sys import version_info
from sleekxmpp.plugins.xep_0048 import *
from core import JID
from common import safeJID
from config import config
log = logging.getLogger(__name__)
......@@ -204,7 +204,7 @@ def get_local():
return
rooms = rooms.split(':')
for room in rooms:
jid = JID(room)
jid = safeJID(room)
if jid.bare == '':
continue
if jid.resource != '':
......
......@@ -10,6 +10,7 @@ various useful functions
"""
from datetime import datetime, timedelta
from sleekxmpp import JID, InvalidJID
import base64
import os
import mimetypes
......@@ -265,3 +266,9 @@ def parse_command_args_to_alias(arg, strto):
else:
var_num = True
return dest
def safeJID(*args, **kwargs):
try:
return JID(*args, **kwargs)
except InvalidJID:
return JID('')
......@@ -13,7 +13,8 @@ the roster.
import logging
log = logging.getLogger(__name__)
from sleekxmpp.xmlstream import JID
from sleekxmpp import JID
from common import safeJID
class Resource(object):
"""
......@@ -24,7 +25,7 @@ class Resource(object):
"""
data: the dict to use as a source
"""
self._jid = JID(jid) # Full jid
self._jid = safeJID(jid) # Full jid
self._data = data
@property
......@@ -110,7 +111,7 @@ class Contact(object):
return self.__item['subscription']
def __contains__(self, value):
return value in self.__item.resources or JID(value).resource in self.__item.resources
return value in self.__item.resources or safeJID(value).resource in self.__item.resources
def __len__(self):
"""Number of resources"""
......@@ -122,7 +123,7 @@ class Contact(object):
def __getitem__(self, key):
"""Return the corresponding Resource object, or None"""
res = JID(key).resource
res = safeJID(key).resource
resources = self.__item.resources
item = resources.get(res, None) or resources.get(key, None)
return Resource(key, item) if item else None
......
......@@ -25,6 +25,7 @@ import singleton
import collections
from sleekxmpp import JID, InvalidJID
from common import safeJID
from sleekxmpp.xmlstream.stanzabase import StanzaBase
from sleekxmpp.xmlstream.handler import Callback
......@@ -624,7 +625,7 @@ class Core(object):
If none already exist, and create is "True", we create it
and return it. Otherwise, we return None
"""
jid = JID(jid)
jid = safeJID(jid)
# We first check if we have a conversation opened with this precise resource
conversation = self.get_tab_by_name(jid.full, tabs.ConversationTab)
if not conversation:
......@@ -1343,7 +1344,7 @@ class Core(object):
if self.current_tab() == start:
break
else:
while nb not in JID(self.current_tab().get_name()).user:
while nb not in safeJID(self.current_tab().get_name()).user:
self.tabs.append(self.tabs.pop(0))
if self.current_tab() is start:
break
......@@ -1352,7 +1353,7 @@ class Core(object):
def completion_win(self, the_input):
"""Completion for /win"""
l = [JID(tab.get_name()).user for tab in self.tabs]
l = [safeJID(tab.get_name()).user for tab in self.tabs]
l.remove('')
return the_input.auto_completion(l, ' ', quotify=False)
......@@ -1365,14 +1366,11 @@ class Core(object):
if len(arg) > 1:
return self.command_help('list')
elif arg:
try:
server = JID(arg[0]).server
except InvalidJID:
server = JID('')
server = safeJID(arg[0]).server
else:
if not isinstance(self.current_tab(), tabs.MucTab):
return self.information('Please provide a server', 'Error')
server = JID(self.current_tab().get_name()).server
server = safeJID(self.current_tab().get_name()).server
list_tab = tabs.MucListTab(server)
self.add_tab(list_tab, True)
self.xmpp.plugin['xep_0030'].get_items(jid=server, block=False, callback=list_tab.on_muc_list_item_received)
......@@ -1383,7 +1381,7 @@ class Core(object):
for tab in self.tabs: # TODO, also from an history
if isinstance(tab, tabs.MucTab) and\
tab.get_name() not in muc_serv_list:
muc_serv_list.append(JID(tab.get_name()).server)
muc_serv_list.append(safeJID(tab.get_name()).server)
if muc_serv_list:
return the_input.auto_completion(muc_serv_list, ' ', quotify=False)
......@@ -1403,10 +1401,7 @@ class Core(object):
args = common.shell_split(arg)
if len(args) < 1:
return self.command_help('version')
try:
jid = JID(args[0])
except InvalidJID:
jid = JID('')
jid = safeJID(args[0])
if jid.resource or jid not in roster:
self.xmpp.plugin['xep_0092'].get_version(jid, callback=callback)
elif jid in roster:
......@@ -1434,13 +1429,10 @@ class Core(object):
tab = self.current_tab()
if not isinstance(tab, tabs.MucTab) and not isinstance(tab, tabs.PrivateTab):
return
room = JID(tab.get_name()).bare
room = safeJID(tab.get_name()).bare
nick = tab.own_nick
else:
try:
info = JID(args[0])
except InvalidJID:
info = JID('')
info = safeJID(args[0])
if info.resource == '':
default = os.environ.get('USER') if os.environ.get('USER') else 'poezio'
nick = config.get('default_nick', '')
......@@ -1462,7 +1454,7 @@ class Core(object):
# check if the current room's name has a server
if isinstance(self.current_tab(), tabs.MucTab) and\
self.current_tab().get_name().find('@') != -1:
room += '@%s' % JID(self.current_tab().get_name()).domain
room += '@%s' % safeJID(self.current_tab().get_name()).domain
else: # no server could be found, print a message and return
self.information(_("You didn't specify a server for the room you want to join"), 'Error')
return
......@@ -1512,10 +1504,7 @@ class Core(object):
if len(txt.split()) != 2:
# we are not on the 1st argument of the command line
return False
try:
jid = JID(txt.split()[1])
except InvalidJID:
jid = JID('')
jid = safeJID(txt.split()[1])
if jid.server:
if jid.resource or jid.full.endswith('/'):
# we are writing the resource: complete the node
......@@ -1540,7 +1529,7 @@ class Core(object):
serv_list = []
for tab in self.tabs:
if isinstance(tab, tabs.MucTab):
serv_list.append('%s@%s'% (jid.user, JID(tab.get_name()).host))
serv_list.append('%s@%s'% (jid.user, safeJID(tab.get_name()).host))
serv_list.extend(list(self.pending_invites.keys()))
the_input.auto_completion(serv_list, '')
return True
......@@ -1572,10 +1561,7 @@ class Core(object):
self.information('Bookmarks added and saved.', 'Info')
return
else:
try:
info = JID(args[0])
except InvalidJID:
return self.information('Invalid JID.', 'Error')
info = safeJID(args[0])
if info.resource != '':
nick = info.resource
roomname = info.bare
......@@ -1608,12 +1594,9 @@ class Core(object):
n += 1
if len(args) == 1:
jid = JID('')
jid = safeJID('')
else:
try:
jid = JID(args[1])
except InvalidJID:
jid = JID('')
jid = safeJID(args[1])
if len(args) > 2:
return
if jid.server and (jid.resource or jid.full.endswith('/')):
......@@ -1673,10 +1656,7 @@ class Core(object):
self.information("Could not add the bookmarks.", "Info")
return
else:
try:
info = JID(args[0])
except InvalidJID:
return self.information('Invalid JID.', 'Error')
info = safeJID(args[0])
if info.resource != '':
nick = info.resource
roomname = info.bare
......@@ -1717,12 +1697,9 @@ class Core(object):
n += 1
if len(args) == 1:
jid = JID('')
jid = safeJID('')
else:
try:
jid = JID(args[1])
except InvalidJID:
jid = JID('')
jid = safeJID(args[1])
if len(args) == 2:
return the_input.auto_completion(['true', 'false'], '')
......@@ -1869,12 +1846,12 @@ class Core(object):
message = args[1]
else:
if isinstance(tab, tabs.MucTab):
domain = JID(tab.get_name()).domain
domain = safeJID(tab.get_name()).domain
else:
self.information(_("No server specified"), "Error")
return
for tab in self.tabs:
if isinstance(tab, tabs.MucTab) and JID(tab.get_name()).domain == domain:
if isinstance(tab, tabs.MucTab) and safeJID(tab.get_name()).domain == domain:
if tab.joined:
muc.leave_groupchat(tab.core.xmpp, tab.get_name(), tab.own_nick, message)
tab.joined = False
......@@ -1891,7 +1868,7 @@ class Core(object):
serv_list = []
for tab in self.tabs:
if isinstance(tab, tabs.MucTab):
serv = JID(tab.get_name()).server
serv = safeJID(tab.get_name()).server
if not serv in serv_list:
serv_list.append(serv)
return the_input.auto_completion(serv_list, ' ')
......@@ -1910,7 +1887,7 @@ class Core(object):
seconds = iq['last_activity']['seconds']
status = iq['last_activity']['status']
from_ = iq['from']
if not JID(from_).user:
if not safeJID(from_).user:
msg = 'The uptime of %s is %s.' % (
from_,
common.parse_secs_to_str(seconds))
......@@ -1920,11 +1897,7 @@ class Core(object):
common.parse_secs_to_str(seconds),
(' and his/her last status was %s' % status) if status else '',)
self.information(msg, 'Info')
try:
jid = JID(arg)
except InvalidJID:
self.information('No valid JID given', 'Error')
return
jid = safeJID(arg)
self.xmpp.plugin['xep_0012'].get_last_activity(jid, block=False, callback=callback)
def completion_activity(self, the_input):
......@@ -1961,10 +1934,7 @@ class Core(object):
args = common.shell_split(arg)
if not len(args):
return
try:
jid = JID(args[0])
except InvalidJID:
jid = JID('')
jid = safeJID(args[0])
if jid.bare not in self.pending_invites:
return
reason = args[1] if len(args) > 1 else ''
......@@ -1987,7 +1957,7 @@ class Core(object):
"""/invitations"""
build = ""
for invite in self.pending_invites:
build += "%s by %s" % (invite, JID(self.pending_invites[invite]).bare)
build += "%s by %s" % (invite, safeJID(self.pending_invites[invite]).bare)
if self.pending_invites:
build = "You are invited to the following rooms:\n" + build
else:
......
......@@ -17,7 +17,8 @@ from contact import Contact
from roster_sorting import SORTING_METHODS, GROUP_SORTING_METHODS
from os import path as p
from sleekxmpp.xmlstream.stanzabase import JID
from common import safeJID
from sleekxmpp import JID
from sleekxmpp.exceptions import IqError
......@@ -48,7 +49,7 @@ class Roster(object):
def __getitem__(self, key):
"""Get a Contact from his bare JID"""
key = JID(key).bare
key = safeJID(key).bare
if key in self.contacts and self.contacts[key] is not None:
return self.contacts[key]
if key in self.jids():
......@@ -62,7 +63,7 @@ class Roster(object):
def __delitem__(self, jid):
"""Remove a contact from the roster"""
jid = JID(jid).bare
jid = safeJID(jid).bare
contact = self[jid]
if not contact:
return
......@@ -85,7 +86,7 @@ class Roster(object):
def __contains__(self, key):
"""True if the bare jid is in the roster, false otherwise"""
return JID(key).bare in self.jids()
return safeJID(key).bare in self.jids()
@property
def jid(self):
......@@ -120,7 +121,7 @@ class Roster(object):
def jids(self):
"""List of the contact JIDS"""
return [key for key in self.__node.keys() if JID(key).server not in self.blacklist and key != self.jid]
return [key for key in self.__node.keys() if safeJID(key).server not in self.blacklist and key != self.jid]
def get_contacts(self):
"""
......
......@@ -39,6 +39,7 @@ import multiuserchat as muc
from theming import get_theme
from common import safeJID
from sleekxmpp import JID, InvalidJID
from sleekxmpp.xmlstream import matcher
from sleekxmpp.xmlstream.handler import Callback
......@@ -804,13 +805,10 @@ class MucTab(ChatTab):
if not arg:
return self.core.command_help('version')
if arg in [user.nick for user in self.users]:
jid = JID(self.name)
jid = safeJID(self.name)
jid.resource = arg
else:
try:
jid = JID(arg)
except InvalidJID:
jid = JID('')
jid = safeJID(arg)
self.core.xmpp.plugin['xep_0092'].get_version(jid, callback=callback)
def command_nick(self, arg):
......@@ -1147,7 +1145,7 @@ class MucTab(ChatTab):
def get_nick(self):
if config.getl('show_muc_jid', 'true') == 'false':
return JID(self.name).user
return safeJID(self.name).user
return self.name
def get_text_window(self):
......@@ -1200,7 +1198,7 @@ class MucTab(ChatTab):
self.core.events.trigger('muc_join', presence, self)
if from_nick == self.own_nick:
self.joined = True
roster.blacklist.add(JID(from_room).server)
roster.blacklist.add(safeJID(from_room).server)
if self.get_name() in self.core.initial_joins:
self.core.initial_joins.remove(self.get_name())
self._state = 'normal'
......@@ -1297,7 +1295,7 @@ class MucTab(ChatTab):
self.own_nick = new_nick
# also change our nick in all private discussion of this room
for _tab in self.core.tabs:
if isinstance(_tab, PrivateTab) and JID(_tab.get_name()).bare == self.name:
if isinstance(_tab, PrivateTab) and safeJID(_tab.get_name()).bare == self.name:
_tab.own_nick = new_nick
user.change_nick(new_nick)
color = user.color[0] if config.get_by_tabname('display_user_color_in_join_part', '', self.general_jid, True) == 'true' else 3
......@@ -1579,7 +1577,7 @@ class PrivateTab(ChatTab):
self.commands['close'] = (self.command_unquery, _("Usage: /close\nClose: Close the tab."), None)
self.commands['version'] = (self.command_version, _('Usage: /version\nVersion: Get the software version of the current interlocutor (usually its XMPP client and Operating System).'), None)
self.resize()
self.parent_muc = self.core.get_tab_by_name(JID(name).bare, MucTab)
self.parent_muc = self.core.get_tab_by_name(safeJID(name).bare, MucTab)
self.on = True
self.update_commands()
self.update_keys()
......@@ -1689,7 +1687,7 @@ class PrivateTab(ChatTab):
if arg:
self.parent_muc.command_info(arg)
else:
user = JID(self.name).resource
user = safeJID(self.name).resource
self.parent_muc.command_info(user)
def resize(self):
......@@ -1719,7 +1717,7 @@ class PrivateTab(ChatTab):
return self.name
def get_nick(self):
return JID(self.name).resource
return safeJID(self.name).resource
def on_input(self, key, raw):
if not raw and key in self.key_func:
......@@ -1729,7 +1727,7 @@ class PrivateTab(ChatTab):
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(JID(self.name).bare, MucTab)
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
......@@ -1738,7 +1736,7 @@ class PrivateTab(ChatTab):
self.state = 'normal'
self.text_win.remove_line_separator()
self.text_win.add_line_separator(self._text_buffer)
tab = self.core.get_tab_by_name(JID(self.name).bare, MucTab)
tab = self.core.get_tab_by_name(safeJID(self.name).bare, MucTab)
if tab and tab.joined and config.get_by_tabname(
'send_chat_states', 'true', self.general_jid, True) == 'true'\
and not self.input.get_text() and self.on:
......@@ -1747,7 +1745,7 @@ class PrivateTab(ChatTab):
def on_gain_focus(self):
self.state = 'current'
curses.curs_set(1)
tab = self.core.get_tab_by_name(JID(self.name).bare, MucTab)
tab = self.core.get_tab_by_name(safeJID(self.name).bare, MucTab)
if tab and tab.joined and config.get_by_tabname(
'send_chat_states', 'true', self.general_jid, True) == 'true'\
and not self.input.get_text() and self.on:
......@@ -1768,7 +1766,7 @@ class PrivateTab(ChatTab):
display a message.
"""
self.add_message('\x193}%(old)s\x19%(info_col)s} is now known as \x193}%(new)s' % {'old':old_nick, 'new':new_nick, 'info_col': get_theme().COLOR_INFORMATION_TEXT[0]})
new_jid = JID(self.name).bare+'/'+new_nick
new_jid = safeJID(self.name).bare+'/'+new_nick
self.name = new_jid
def user_left(self, status_message, from_nick):
......@@ -1789,7 +1787,7 @@ class PrivateTab(ChatTab):
The user (or at least someone with the same nick) came back in the MUC
"""
self.activate()
tab = self.core.get_tab_by_name(JID(self.name).bare, MucTab)
tab = self.core.get_tab_by_name(safeJID(self.name).bare, MucTab)
color = 3
if tab and config.get_by_tabname('display_user_color_in_join_part', '', self.general_jid, True):
user = tab.get_user_by_name(nick)
......@@ -1910,10 +1908,7 @@ class RosterInfoTab(Tab):
item = self.roster_win.selected_row
if arg:
try:
jid = JID(arg)
except InvalidJID:
jid = JID('')
jid = safeJID(arg)
elif isinstance(item, Contact):
jid = item.bare_jid
elif isinstance(item, Resource):
......@@ -1939,10 +1934,7 @@ class RosterInfoTab(Tab):
item = self.roster_win.selected_row
if arg:
try:
jid = JID(arg)
except InvalidJID:
jid = JID('')
jid = safeJID(arg)
elif isinstance(item, Contact):
jid = item.bare_jid
elif isinstance(item, Resource):
......@@ -2062,10 +2054,7 @@ class RosterInfoTab(Tab):
self.core.information('No subscription to deny')
return
else:
try:
jid = JID(arg).bare
except InvalidJID:
jid = JID('')
jid = safeJID(arg).bare
if not jid in [jid for jid in roster.jids()]:
self.core.information('No subscription to deny')
return
......@@ -2079,10 +2068,7 @@ class RosterInfoTab(Tab):
Add the specified JID to the roster, and set automatically
accept the reverse subscription
"""
try:
jid = JID(JID(args.strip()).bare)
except InvalidJID:
return self.core.information('Invalid JID.', 'Error')
jid = safeJID(safeJID(args.strip()).bare)
if not jid:
self.core.information(_('No JID specified'), 'Error')
return
......@@ -2097,10 +2083,7 @@ class RosterInfoTab(Tab):
args = common.shell_split(arg)
if not args:
return self.core.command_help('name')
try:
jid = JID(args[0]).bare
except InvalidJID:
jid = JID('')
jid = safeJID(args[0]).bare
name = args[1] if len(args) == 2 else ''
contact = roster[jid]
......@@ -2120,10 +2103,7 @@ class RosterInfoTab(Tab):
args = common.shell_split(args)
if len(args) != 2:
return
try:
jid = JID(args[0]).bare
except InvalidJID:
jid = JID('')
jid = safeJID(args[0]).bare
group = args[1]
contact = roster[jid]
......@@ -2154,10 +2134,7 @@ class RosterInfoTab(Tab):
args = common.shell_split(arg)
if len(args) != 3:
return self.core.command_help('groupmove')
try:
jid = JID(args[0]).bare
except InvalidJID:
jid = JID('')
jid = safeJID(args[0]).bare
group_from = args[1]
group_to = args[2]
......@@ -2203,10 +2180,7 @@ class RosterInfoTab(Tab):
args = common.shell_split(args)
if len(args) != 2:
return
try:
jid = JID(args[0]).bare
except InvalidJID:
jid = JID('')
jid = safeJID(args[0]).bare
group = args[1]
contact = roster[jid]
......@@ -2235,10 +2209,7 @@ class RosterInfoTab(Tab):
from its presence, and cancel its subscription to our.
"""
if args.strip():
try:
jid = JID(args.strip()).bare
except InvalidJID:
jid = JID('')
jid = safeJID(args.strip()).bare
else:
item = self.roster_win.selected_row
if isinstance(item, Contact):
......@@ -2299,7 +2270,7 @@ class RosterInfoTab(Tab):
def completion_remove(self, the_input):
"""
From with any JID presence in the roster
Completion for /remove
"""
jids = [jid for jid in roster.jids()]
return the_input.auto_completion(jids, '', quotify=False)
......@@ -2395,10 +2366,7 @@ class RosterInfoTab(Tab):
self.core.information('No subscription to accept')
return
else:
try:
jid = JID(arg).bare
except InvalidJID:
jid = JID('')
jid = safeJID(arg).bare
contact = roster[jid]
if contact is None:
return
......@@ -2607,7 +2575,7 @@ class RosterInfoTab(Tab):
if isinstance(selected_row, Contact):
jid = selected_row.bare_jid
elif isinstance(selected_row, Resource):
jid = JID(selected_row.jid).bare
jid = safeJID(selected_row.jid).bare
else:
return
self.on_slash()
......@@ -2682,7 +2650,7 @@ class ConversationTab(ChatTab):
@property
def general_jid(self):
return JID(self.get_name()).bare
return safeJID(self.get_name()).bare
@staticmethod
def add_information_element(plugin_name, callback):
......@@ -2719,7 +2687,7 @@ class ConversationTab(ChatTab):
msg['attention'] = True
self.core.events.trigger('conversation_say_after', msg, self)
msg.send()
logger.log_message(JID(self.get_name()).bare, self.core.own_nick, line)
logger.log_message(safeJID(self.get_name()).bare, self.core.own_nick, line)
self.cancel_paused_delay()
self.text_win.refresh()
self.input.refresh()
......@@ -2742,7 +2710,7 @@ class ConversationTab(ChatTab):
status = iq['last_activity']['status']
from_ = iq['from']
msg = '\x19%s}The last activity of %s was %s ago%s'
if not JID(from_).user:
if not safeJID(from_).user:
msg = '\x19%s}The uptime of %s is %s.' % (
get_theme().COLOR_INFORMATION_TEXT[0],
from_,
......@@ -2760,7 +2728,7 @@ class ConversationTab(ChatTab):
def command_info(self, arg):
contact = roster[self.get_name()]
jid = JID(self.get_name())
jid = safeJID(self.get_name())
if jid.resource:
resource = contact[jid.full]
else:
......@@ -2808,7 +2776,7 @@ class ConversationTab(ChatTab):
if arg:
return self.core.command_version(arg)
jid = self.name
jid = JID(jid)
jid = safeJID(jid)
if not jid.resource:
if jid in roster:
resource = roster[jid].get_highest_priority_resource()
......@@ -2837,7 +2805,7 @@ class ConversationTab(ChatTab):
self.input.refresh()
def refresh_info_header(self):
self.info_header.refresh(self.get_name(), roster[self.get_name()] or JID(self.get_name()).user,
self.info_header.refresh(self.get_name(), roster[self.get_name()] or safeJID(self.get_name()).user,