Unverified Commit ea2d7686 authored by mathieui's avatar mathieui

yapf -rip

parent 3ec153a6
......@@ -316,16 +316,18 @@ class Config(RawConfigParser):
sections, result_lines = result
if section not in sections:
log.error('Tried to remove the option %s from a non-'
'existing section (%s)', option, section)
log.error(
'Tried to remove the option %s from a non-'
'existing section (%s)', option, section)
return True
else:
begin, end = sections[section]
pos = find_line(result_lines, begin, end, option)
if pos is -1:
log.error('Tried to remove a non-existing option %s'
' from section %s', option, section)
log.error(
'Tried to remove a non-existing option %s'
' from section %s', option, section)
return True
else:
del result_lines[pos]
......@@ -338,7 +340,8 @@ class Config(RawConfigParser):
before copying it to the final destination
"""
try:
filename = self.file_name.parent / ('.%s.tmp' % self.file_name.name)
filename = self.file_name.parent / (
'.%s.tmp' % self.file_name.name)
with os.fdopen(
os.open(
str(filename),
......@@ -423,9 +426,10 @@ class Config(RawConfigParser):
elif current.lower() == "true":
value = "false"
else:
return ('Could not toggle option: %s.'
' Current value is %s.' %
(option, current or "empty"), 'Warning')
return (
'Could not toggle option: %s.'
' Current value is %s.' % (option, current or "empty"),
'Warning')
if self.has_section(section):
RawConfigParser.set(self, section, option, value)
else:
......@@ -555,10 +559,12 @@ def run_cmdline_args():
try:
options.filename.parent.mkdir(parents=True, exist_ok=True)
except OSError as e:
sys.stderr.write('Poezio was unable to create the config directory: %s\n' % e)
sys.stderr.write(
'Poezio was unable to create the config directory: %s\n' % e)
sys.exit(1)
default = Path(__file__).parent / '..' / 'data' / 'default_config.cfg'
other = Path(pkg_resources.resource_filename('poezio', 'default_config.cfg'))
other = Path(
pkg_resources.resource_filename('poezio', 'default_config.cfg'))
if default.is_file():
copy2(str(default), str(options.filename))
elif other.is_file():
......@@ -568,8 +574,8 @@ def run_cmdline_args():
# file is readonly, so is the copy.
# Make it writable by the user who just created it.
if options.filename.exists():
options.filename.chmod(
options.filename.stat().st_mode | stat.S_IWUSR)
options.filename.chmod(options.filename.stat().st_mode
| stat.S_IWUSR)
global firstrun
firstrun = True
......
......@@ -82,7 +82,9 @@ class Connection(slixmpp.ClientXMPP):
jid = config.get('server')
password = None
jid = safeJID(jid)
jid.resource = '%s-%s' % (jid.resource, device_id) if jid.resource else 'poezio-%s' % device_id
jid.resource = '%s-%s' % (
jid.resource,
device_id) if jid.resource else 'poezio-%s' % device_id
# TODO: use the system language
slixmpp.ClientXMPP.__init__(
self, jid, password, lang=config.get('lang'))
......@@ -108,8 +110,9 @@ class Connection(slixmpp.ClientXMPP):
self.auto_authorize = None
# prosody defaults, lowest is AES128-SHA, it should be a minimum
# for anything that came out after 2002
self.ciphers = config.get('ciphers', 'HIGH+kEDH:HIGH+kEECDH:HIGH:!PSK'
':!SRP:!3DES:!aNULL')
self.ciphers = config.get(
'ciphers', 'HIGH+kEDH:HIGH+kEECDH:HIGH:!PSK'
':!SRP:!3DES:!aNULL')
self.ca_certs = config.get('ca_cert_path') or None
interval = config.get('whitespace_interval')
if int(interval) > 0:
......@@ -119,11 +122,17 @@ class Connection(slixmpp.ClientXMPP):
self.register_plugin('xep_0004')
self.register_plugin('xep_0012')
# Must be loaded before 0030.
self.register_plugin('xep_0115', {
'caps_node': 'https://poez.io',
'cache': FileSystemCache(str(xdg.CACHE_HOME), 'caps', encode=str,
decode=lambda x: DiscoInfo(ET.fromstring(x))),
})
self.register_plugin(
'xep_0115', {
'caps_node':
'https://poez.io',
'cache':
FileSystemCache(
str(xdg.CACHE_HOME),
'caps',
encode=str,
decode=lambda x: DiscoInfo(ET.fromstring(x))),
})
self.register_plugin('xep_0030')
self.register_plugin('xep_0045')
self.register_plugin('xep_0048')
......
......@@ -552,10 +552,10 @@ class CommandCore:
theme.COLOR_INFORMATION_TEXT),
})
for option_name, option_value in section.items():
lines.append('%s\x19%s}=\x19o%s' %
(option_name,
dump_tuple(theme.COLOR_REVISIONS_MESSAGE),
option_value))
lines.append(
'%s\x19%s}=\x19o%s' %
(option_name, dump_tuple(
theme.COLOR_REVISIONS_MESSAGE), option_value))
info = ('Current options:\n%s' % '\n'.join(lines), 'Info')
elif len(args) == 1:
option = args[0]
......@@ -570,7 +570,8 @@ class CommandCore:
section = plugin_name
option = args[1]
if plugin_name not in self.core.plugin_manager.plugins:
file_name = self.core.plugin_manager.plugins_conf_dir / (plugin_name + '.cfg')
file_name = self.core.plugin_manager.plugins_conf_dir / (
plugin_name + '.cfg')
plugin_config = PluginConfig(file_name, plugin_name)
else:
plugin_config = self.core.plugin_manager.plugins[
......@@ -597,7 +598,8 @@ class CommandCore:
option = args[1]
value = args[2]
if plugin_name not in self.core.plugin_manager.plugins:
file_name = self.core.plugin_manager.plugins_conf_dir / (plugin_name + '.cfg')
file_name = self.core.plugin_manager.plugins_conf_dir / (
plugin_name + '.cfg')
plugin_config = PluginConfig(file_name, plugin_name)
else:
plugin_config = self.core.plugin_manager.plugins[
......@@ -685,8 +687,9 @@ class CommandCore:
"Callback for the last activity"
if iq['type'] != 'result':
if iq['error']['type'] == 'auth':
self.core.information('You are not allowed to see the '
'activity of this contact.', 'Error')
self.core.information(
'You are not allowed to see the '
'activity of this contact.', 'Error')
else:
self.core.information('Error retrieving the activity',
'Error')
......@@ -753,8 +756,9 @@ class CommandCore:
specific = args[1]
text = args[2]
if specific and specific not in pep.ACTIVITIES[general]:
return self.core.information('%s is not a correct value '
'for an activity' % specific, 'Error')
return self.core.information(
'%s is not a correct value '
'for an activity' % specific, 'Error')
self.core.xmpp.plugin['xep_0108'].publish_activity(
general, specific, text, callback=dumb_callback)
......@@ -928,8 +932,9 @@ class CommandCore:
"""
/plugins
"""
self.core.information("Plugins currently in use: %s" % repr(
list(self.core.plugin_manager.plugins.keys())), 'Info')
self.core.information(
"Plugins currently in use: %s" % repr(
list(self.core.plugin_manager.plugins.keys())), 'Info')
@command_args_parser.quoted(1, 1)
def message(self, args):
......
......@@ -67,7 +67,8 @@ class CompletionCore:
def theme(self, the_input):
""" Completion for /theme"""
themes_dir = config.get('themes_dir')
themes_dir = Path(themes_dir).expanduser() if themes_dir else xdg.DATA_HOME / 'themes'
themes_dir = Path(themes_dir).expanduser(
) if themes_dir else xdg.DATA_HOME / 'themes'
try:
theme_files = [
name.stem for name in themes_dir.iterdir()
......@@ -131,8 +132,8 @@ class CompletionCore:
serv_list = []
for tab in self.core.get_tabs(tabs.MucTab):
if tab.joined:
serv_list.append('%s@%s' % (jid.user,
safeJID(tab.name).host))
serv_list.append(
'%s@%s' % (jid.user, safeJID(tab.name).host))
serv_list.extend(relevant_rooms)
return Completion(
the_input.new_completion, serv_list, 1, quotify=True)
......
......@@ -77,7 +77,8 @@ class Core:
self.bookmarks = BookmarkList()
self.debug = False
self.remote_fifo = None
self.avatar_cache = FileSystemPerJidCache(str(xdg.CACHE_HOME), 'avatars', binary=True)
self.avatar_cache = FileSystemPerJidCache(
str(xdg.CACHE_HOME), 'avatars', binary=True)
# a unique buffer used to store global information
# that are displayed in almost all tabs, in an
# information window.
......@@ -320,10 +321,10 @@ class Core:
self.on_request_receipts_config_change)
self.add_configuration_handler("ack_message_receipts",
self.on_ack_receipts_config_change)
self.add_configuration_handler("plugins_dir",
self.plugin_manager.on_plugins_dir_change)
self.add_configuration_handler("plugins_conf_dir",
self.plugin_manager.on_plugins_conf_dir_change)
self.add_configuration_handler(
"plugins_dir", self.plugin_manager.on_plugins_dir_change)
self.add_configuration_handler(
"plugins_conf_dir", self.plugin_manager.on_plugins_conf_dir_change)
self.add_configuration_handler("connection_timeout_delay",
self.xmpp.set_keepalive_values)
self.add_configuration_handler("connection_check_interval",
......@@ -676,8 +677,9 @@ class Core:
ok = ok and config.silent_set('info_win_height',
self.information_win_size, 'var')
if not ok:
self.information('Unable to save runtime preferences'
' in the config file', 'Error')
self.information(
'Unable to save runtime preferences'
' in the config file', 'Error')
def on_roster_enter_key(self, roster_row):
"""
......@@ -767,15 +769,15 @@ class Core:
filename = os.path.join(fifo_path, 'poezio.fifo')
if not self.remote_fifo:
try:
self.remote_fifo = Fifo(
filename, 'w')
self.remote_fifo = Fifo(filename, 'w')
except (OSError, IOError) as exc:
log.error(
'Could not open the fifo for writing (%s)',
filename,
exc_info=True)
self.information('Could not open the fifo '
'file for writing: %s' % exc, 'Error')
self.information(
'Could not open the fifo '
'file for writing: %s' % exc, 'Error')
return
args = (pipes.quote(arg.replace('\n', ' ')) for arg in command)
......@@ -862,8 +864,9 @@ class Core:
msg = msg.replace('\n', '|') if msg else ''
ok = ok and config.silent_set('status_message', msg)
if not ok:
self.information('Unable to save the status in '
'the config file', 'Error')
self.information(
'Unable to save the status in '
'the config file', 'Error')
def get_bookmark_nickname(self, room_name):
"""
......@@ -1420,8 +1423,7 @@ class Core:
if typ.lower() in filter_types:
log.debug(
'Did not show the message:\n\t%s> %s \n\tdue to '
'information_buffer_type_filter configuration',
typ, msg)
'information_buffer_type_filter configuration', typ, msg)
return False
filter_messages = config.get('filter_info_messages').split(':')
for words in filter_messages:
......@@ -2076,9 +2078,9 @@ class Core:
type_ = iq['error']['type']
condition = iq['error']['condition']
if not (type_ == 'cancel' and condition == 'item-not-found'):
self.information('Unable to fetch the remote'
' bookmarks; %s: %s' % (type_, condition),
'Error')
self.information(
'Unable to fetch the remote'
' bookmarks; %s: %s' % (type_, condition), 'Error')
return
remote_bookmarks = self.bookmarks.remote()
self.join_initial_rooms(remote_bookmarks)
......
......@@ -138,8 +138,9 @@ class HandlerCore:
sent = message['carbon_sent']
# todo: implement proper MUC detection logic
if (sent['to'].resource and (sent['to'].bare not in roster
or roster[sent['to'].bare].subscription == 'none')):
if (sent['to'].resource
and (sent['to'].bare not in roster
or roster[sent['to'].bare].subscription == 'none')):
fixes.has_identity(
self.core.xmpp,
sent['to'].server,
......@@ -276,9 +277,7 @@ class HandlerCore:
message['from'].bare)
tmp_dir = get_image_cache()
body = xhtml.get_body_from_message_stanza(
message,
use_xhtml=use_xhtml,
extract_images_to=tmp_dir)
message, use_xhtml=use_xhtml, extract_images_to=tmp_dir)
if not body:
if not self.core.xmpp.plugin['xep_0380'].has_eme(message):
return
......@@ -332,9 +331,7 @@ class HandlerCore:
if not message['body']:
return
body = xhtml.get_body_from_message_stanza(
message,
use_xhtml=use_xhtml,
extract_images_to=tmp_dir)
message, use_xhtml=use_xhtml, extract_images_to=tmp_dir)
delayed, date = common.find_delayed_tag(message)
def try_modify():
......@@ -395,7 +392,8 @@ class HandlerCore:
avatar_hash = info['id']
# First check whether we have it in cache.
cached_avatar = self.core.avatar_cache.retrieve_by_jid(jid, avatar_hash)
cached_avatar = self.core.avatar_cache.retrieve_by_jid(
jid, avatar_hash)
if cached_avatar:
contact.avatar = cached_avatar
log.debug('Using cached avatar for %s', jid)
......@@ -404,9 +402,8 @@ class HandlerCore:
# If we didn’t have any, query the data instead.
if not info['url']:
try:
result = await self.core.xmpp[
'xep_0084'].retrieve_avatar(
jid, avatar_hash, timeout=60)
result = await self.core.xmpp['xep_0084'].retrieve_avatar(
jid, avatar_hash, timeout=60)
avatar = result['pubsub']['items']['item']['avatar_data'][
'value']
if sha1(avatar).hexdigest().lower() != avatar_hash.lower():
......@@ -421,7 +418,8 @@ class HandlerCore:
log.debug('Received %s avatar: %s', jid, info['type'])
# Now we save the data on the file system to not have to request it again.
if not self.core.avatar_cache.store_by_jid(jid, avatar_hash, contact.avatar):
if not self.core.avatar_cache.store_by_jid(
jid, avatar_hash, contact.avatar):
log.debug(
'Failed writing %s’s avatar to cache:',
jid,
......@@ -437,7 +435,8 @@ class HandlerCore:
log.debug('Received vCard avatar update from %s: %s', jid, avatar_hash)
# First check whether we have it in cache.
cached_avatar = self.core.avatar_cache.retrieve_by_jid(jid, avatar_hash)
cached_avatar = self.core.avatar_cache.retrieve_by_jid(
jid, avatar_hash)
if cached_avatar:
contact.avatar = cached_avatar
log.debug('Using cached avatar for %s', jid)
......@@ -458,8 +457,10 @@ class HandlerCore:
log.debug('Received %s avatar: %s', jid, avatar['TYPE'])
# Now we save the data on the file system to not have to request it again.
if not self.core.avatar_cache.store_by_jid(jid, avatar_hash, contact.avatar):
log.debug('Failed writing %s’s avatar to cache:', jid, exc_info=True)
if not self.core.avatar_cache.store_by_jid(jid, avatar_hash,
contact.avatar):
log.debug(
'Failed writing %s’s avatar to cache:', jid, exc_info=True)
def on_nick_received(self, message):
"""
......@@ -509,9 +510,9 @@ class HandlerCore:
'display_gaming_notifications', contact.bare_jid):
if contact.gaming:
self.core.information(
'%s is playing %s' %
(contact.bare_jid,
common.format_gaming_string(contact.gaming)), 'Gaming')
'%s is playing %s' % (contact.bare_jid,
common.format_gaming_string(
contact.gaming)), 'Gaming')
else:
self.core.information(contact.bare_jid + ' stopped playing.',
'Gaming')
......@@ -592,8 +593,9 @@ class HandlerCore:
if old_activity != contact.activity and config.get_by_tabname(
'display_activity_notifications', contact.bare_jid):
if contact.activity:
self.core.information('Activity from ' + contact.bare_jid +
': ' + contact.activity, 'Activity')
self.core.information(
'Activity from ' + contact.bare_jid + ': ' +
contact.activity, 'Activity')
else:
self.core.information(
contact.bare_jid + ' stopped doing his/her activity.',
......@@ -625,9 +627,9 @@ class HandlerCore:
contact.tune = {}
if contact.tune:
logger.log_roster_change(message['from'].bare,
'is now listening to %s' %
common.format_tune_string(contact.tune))
logger.log_roster_change(
message['from'].bare, 'is now listening to %s' %
common.format_tune_string(contact.tune))
if old_tune != contact.tune and config.get_by_tabname(
'display_tune_notifications', contact.bare_jid):
......@@ -668,9 +670,7 @@ class HandlerCore:
use_xhtml = config.get_by_tabname('enable_xhtml_im', room_from)
tmp_dir = get_image_cache()
body = xhtml.get_body_from_message_stanza(
message,
use_xhtml=use_xhtml,
extract_images_to=tmp_dir)
message, use_xhtml=use_xhtml, extract_images_to=tmp_dir)
if not body:
return
......@@ -744,9 +744,7 @@ class HandlerCore:
use_xhtml = config.get_by_tabname('enable_xhtml_im', jid.bare)
tmp_dir = get_image_cache()
body = xhtml.get_body_from_message_stanza(
message,
use_xhtml=use_xhtml,
extract_images_to=tmp_dir)
message, use_xhtml=use_xhtml, extract_images_to=tmp_dir)
tab = self.core.get_tab_by_name(
jid.full,
tabs.PrivateTab) # get the tab with the private conversation
......@@ -755,7 +753,8 @@ class HandlerCore:
if body and not ignore:
tab = self.core.open_private_window(room_from, with_nick,
False)
sender_nick = (tab.own_nick or self.core.own_nick) if sent else with_nick
sender_nick = (tab.own_nick
or self.core.own_nick) if sent else with_nick
if ignore and not sent:
self.core.events.trigger('ignored_private', message, tab)
msg = config.get_by_tabname('private_auto_response', room_from)
......@@ -765,9 +764,7 @@ class HandlerCore:
return
self.core.events.trigger('private_msg', message, tab)
body = xhtml.get_body_from_message_stanza(
message,
use_xhtml=use_xhtml,
extract_images_to=tmp_dir)
message, use_xhtml=use_xhtml, extract_images_to=tmp_dir)
if not body or not tab:
return
replaced = False
......@@ -898,15 +895,16 @@ class HandlerCore:
if iq['type'] == 'error':
error_condition = iq['error']['condition']
error_text = iq['error']['text']
reply = '%s: %s' % (error_condition, error_text) if error_text else error_condition
return self.core.information('Could not get the software '
'version from %s: %s' % (jid, reply),
'Warning')
reply = '%s: %s' % (error_condition,
error_text) if error_text else error_condition
return self.core.information(
'Could not get the software '
'version from %s: %s' % (jid, reply), 'Warning')
res = iq['software_version']
version = '%s is running %s version %s on %s' % (
jid, res.get('name', 'an unknown software'),
res.get('version', 'unknown'),
res.get('os', 'an unknown platform'))
res.get('version', 'unknown'), res.get('os',
'an unknown platform'))
self.core.information(version, 'Info')
### subscription-related handlers ###
......@@ -1127,8 +1125,8 @@ class HandlerCore:
"""
We cannot contact the remote server
"""
self.core.information("Connection to remote server failed: %s" %
(error, ), 'Error')
self.core.information(
"Connection to remote server failed: %s" % (error, ), 'Error')
async def on_disconnected(self, event):
"""
......@@ -1230,8 +1228,8 @@ class HandlerCore:
tab = self.core.get_tab_by_name(room_from, tabs.MucTab)
status_codes = {
s.attrib['code']
for s in message.xml.findall('{%s}x/{%s}status' % (
tabs.NS_MUC_USER, tabs.NS_MUC_USER))
for s in message.xml.findall('{%s}x/{%s}status' %
(tabs.NS_MUC_USER, tabs.NS_MUC_USER))
}
if '101' in status_codes:
self.core.information(
......@@ -1342,9 +1340,8 @@ class HandlerCore:
after = ''
if user:
user_col = dump_tuple(user.color)
user_string = '\x19%s}%s\x19%s}%s' % (user_col, nick_from,
fmt['info_col'],
after)
user_string = '\x19%s}%s\x19%s}%s' % (
user_col, nick_from, fmt['info_col'], after)
else:
user_string = '\x19%s}%s%s' % (fmt['info_col'], nick_from,
after)
......
......@@ -125,9 +125,7 @@ class Logger:
return fd
except IOError:
log.error(
'Unable to open the log file (%s)',
filename,
exc_info=True)
'Unable to open the log file (%s)', filename, exc_info=True)
def get_logs(self, jid, nb=10):
"""
......@@ -151,16 +149,11 @@ class Logger:
try:
fd = filename.open('rb')
except FileNotFoundError:
log.info(
'Non-existing log file (%s)',
filename,
exc_info=True)
log.info('Non-existing log file (%s)', filename, exc_info=True)
return
except OSError:
log.error(
'Unable to open the log file (%s)',
filename,
exc_info=True)
'Unable to open the log file (%s)', filename, exc_info=True)
return
if not fd:
return
......@@ -228,8 +221,7 @@ class Logger:
filename = log_dir / 'roster.log'
if not self._roster_logfile:
try:
self._roster_logfile = filename.open(
'a', encoding='utf-8')
self._roster_logfile = filename.open('a', encoding='utf-8')
except IOError:
log.error(
'Unable to create the log file (%s)',
......@@ -242,8 +234,8 @@ class Logger:
lines = message.split('\n')
first_line = lines.pop(0)
nb_lines = str(len(lines)).zfill(3)
self._roster_logfile.write('MI %s %s %s %s\n' %
(str_time, nb_lines, jid, first_line))
self._roster_logfile.write(
'MI %s %s %s %s\n' % (str_time, nb_lines, jid, first_line))
for line in lines:
self._roster_logfile.write(' %s\n' % line)
self._roster_logfile.flush()
......
......@@ -93,8 +93,8 @@ class PluginManager:
except Exception as e:
log.error('Error while loading the plugin %s', name, exc_info=True)
if notify:
self.core.information('Unable to load the plugin %s: %s' %
(name, e), 'Error')
self.core.information(
'Unable to load the plugin %s: %s' % (name, e), 'Error')
self.unload(name, notify=False)
else:
if notify:
......@@ -130,8 +130,8 @@ class PluginManager:
self.core.information('Plugin %s unloaded' % name, 'Info')
except Exception as e:
log.debug("Could not unload plugin %s", name, exc_info=True)
self.core.information("Could not unload plugin %s: %s" %
(name, e), 'Error')
self.core.information(
"Could not unload plugin %s: %s" % (name, e), 'Error')
def add_command(self,
module_name,
......@@ -327,7 +327,8 @@ class PluginManager:
Create the plugins_conf_dir
"""
plugins_conf_dir = config.get('plugins_conf_dir')
self.plugins_conf_dir = Path(plugins_conf_dir).expanduser() if plugins_conf_dir else xdg.CONFIG_HOME / 'plugins'
self.plugins_conf_dir = Path(plugins_conf_dir).expanduser(
) if plugins_conf_dir else xdg.CONFIG_HOME / 'plugins'
self.check_create_plugins_conf_dir()
def check_create_plugins_conf_dir(self):
......@@ -351,7 +352,8 @@ class PluginManager:
Set the plugins_dir on start
"""
plugins_dir = config.get('plugins_dir')
self.plugins_dir = Path(plugins_dir).expanduser() if plugins_dir else xdg.DATA_HOME / 'plugins'
self.plugins_dir = Path(plugins_dir).expanduser(
) if plugins_dir else xdg.DATA_HOME / 'plugins'
self.check_create_plugins_dir()
def check_create_plugins_dir(self):
......
......@@ -293,8 +293,8 @@ class Tab:
if self.missing_command_callback is not None:
error_handled = self.missing_command_callback(low)
if not error_handled:
self.core.information("Unknown command (%s)" %
(command), 'Error')
self.core.information(
"Unknown command (%s)" % (command), 'Error')
if command in ('correct', 'say'): # hack
arg = xhtml.convert_simple_to_full_colors(arg)
else:
......@@ -685,8 +685,9 @@ class ChatTab(Tab):
'paused')
self.core.add_timed_event(new_event)
self.timed_event_paused = new_event
new_event = timed_events.DelayedEvent(30, self.send_chat_state,