From 53633a5c4c8097c1cb356e5240be2a925fb8a631 Mon Sep 17 00:00:00 2001 From: mathieui Date: Sun, 14 Mar 2021 16:37:01 +0100 Subject: =?UTF-8?q?refactor:=20rewrite=20config.get()=20to=20getbool,=20ge?= =?UTF-8?q?tstr,=20getint=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- poezio/bookmarks.py | 7 +++--- poezio/config.py | 53 +++++++++++++++++++++++++++----------- poezio/connection.py | 52 +++++++++++++++++++------------------- poezio/core/commands.py | 6 ++--- poezio/core/completions.py | 6 ++--- poezio/core/core.py | 60 +++++++++++++++++++++++--------------------- poezio/core/handlers.py | 30 +++++++++++----------- poezio/plugin_e2ee.py | 4 +-- poezio/plugin_manager.py | 4 +-- poezio/roster.py | 3 ++- poezio/tabs/basetabs.py | 10 ++++---- poezio/tabs/muctab.py | 20 +++++++-------- poezio/tabs/privatetab.py | 2 +- poezio/tabs/rostertab.py | 4 +-- poezio/text_buffer.py | 6 ++--- poezio/theming.py | 4 +-- poezio/windows/image.py | 2 +- poezio/windows/info_bar.py | 16 ++++++------ poezio/windows/info_wins.py | 2 +- poezio/windows/inputs.py | 2 +- poezio/windows/muc.py | 4 +-- poezio/windows/roster_win.py | 14 +++++------ poezio/windows/text_win.py | 14 +++++------ poezio/xhtml.py | 2 +- 24 files changed, 176 insertions(+), 151 deletions(-) (limited to 'poezio') diff --git a/poezio/bookmarks.py b/poezio/bookmarks.py index b1ad1f9c..91dc060c 100644 --- a/poezio/bookmarks.py +++ b/poezio/bookmarks.py @@ -163,7 +163,7 @@ class Bookmark: class BookmarkList: def __init__(self): self.bookmarks: List[Bookmark] = [] - preferred = config.get('use_bookmarks_method').lower() + preferred = config.getstr('use_bookmarks_method').lower() if preferred not in ('pep', 'privatexml'): preferred = 'privatexml' self.preferred = preferred @@ -244,7 +244,7 @@ class BookmarkList: async def save(self, xmpp: ClientXMPP, core=None): """Save all the bookmarks.""" self.save_local() - if config.get('use_remote_bookmarks'): + if config.getbool('use_remote_bookmarks'): try: result = await self.save_remote(xmpp) if core is not None: @@ -292,10 +292,9 @@ class BookmarkList: def get_local(self): """Add the locally stored bookmarks to the list.""" - rooms = config.get('rooms') + rooms = config.getlist('rooms') if not rooms: return - rooms = rooms.split(':') for room in rooms: try: jid = JID(room) diff --git a/poezio/config.py b/poezio/config.py index 4f998b6a..c8b04079 100644 --- a/poezio/config.py +++ b/poezio/config.py @@ -19,7 +19,7 @@ import pkg_resources from configparser import RawConfigParser, NoOptionError, NoSectionError from pathlib import Path from shutil import copy2 -from typing import Callable, Dict, List, Optional, Union, Tuple +from typing import Callable, Dict, List, Optional, Union, Tuple, cast from poezio.args import parse_args from poezio import xdg @@ -208,13 +208,13 @@ class Config: try: if isinstance(default, bool): - res = self.getboolean(option, section) + res = self.configparser.getboolean(section, option) elif isinstance(default, int): - res = self.getint(option, section) + res = self.configparser.getint(section, option) elif isinstance(default, float): - res = self.getfloat(option, section) + res = self.configparser.getfloat(section, option) else: - res = self.getstr(option, section) + res = self.configparser.get(section, option) except (NoOptionError, NoSectionError, ValueError, AttributeError): return default if default is not None else '' @@ -222,6 +222,12 @@ class Config: return default return res + def _get_default(self, option, section): + if self.default: + return self.default.get(section, {}).get(option) + else: + return '' + def sections(self, *args, **kwargs): return self.configparser.sections(*args, **kwargs) @@ -287,29 +293,45 @@ class Config: """ return conv(self.__get(option, section, **kwargs)) - def getstr(self, option, section=DEFSECTION): + def getstr(self, option, section=DEFSECTION) -> str: """ get a value and returns it as a string """ - return self.__get(option, section) + try: + return self.configparser.get(section, option) + except (NoOptionError, NoSectionError, ValueError, AttributeError): + return cast(str, self._get_default(option, section)) - def getint(self, option, section=DEFSECTION): + def getint(self, option, section=DEFSECTION) -> int: """ get a value and returns it as an int """ - return self.configparser.getint(section, option) + try: + return self.configparser.getint(section, option) + except (NoOptionError, NoSectionError, ValueError, AttributeError): + return cast(int, self._get_default(option, section)) - def getfloat(self, option, section=DEFSECTION): + def getfloat(self, option, section=DEFSECTION) -> float: """ get a value and returns it as a float """ - return self.configparser.getfloat(section, option) + try: + return self.configparser.getfloat(section, option) + except (NoOptionError, NoSectionError, ValueError, AttributeError): + return cast(float, self._get_default(option, section)) + - def getboolean(self, option, section=DEFSECTION): + def getbool(self, option, section=DEFSECTION) -> bool: """ get a value and returns it as a boolean """ - return self.configparser.getboolean(section, option) + try: + return self.configparser.getboolean(section, option) + except (NoOptionError, NoSectionError, ValueError, AttributeError): + return cast(bool, self._get_default(option, section)) + + def getlist(self, option, section=DEFSECTION) -> List[str]: + return self.getstr(option, section).split(':') def write_in_file(self, section: str, option: str, value: ConfigValue) -> bool: @@ -450,8 +472,8 @@ class Config: # Special case for a 'toggle' value. We take the current value # and set the opposite. Warning if the no current value exists # or it is not a bool. - if value == "toggle": - current = self.get(option, "", section) + if isinstance(value, str) and value == "toggle": + current = self.getbool(option, section) if isinstance(current, bool): value = str(not current) else: @@ -464,6 +486,7 @@ class Config: 'Could not toggle option: %s.' ' Current value is %s.' % (option, current or "empty"), 'Warning') + value = str(value) if self.has_section(section): self.configparser.set(section, option, value) else: diff --git a/poezio/connection.py b/poezio/connection.py index 602a9f36..e474ca94 100644 --- a/poezio/connection.py +++ b/poezio/connection.py @@ -38,24 +38,24 @@ class Connection(slixmpp.ClientXMPP): __init = False def __init__(self): - keyfile = config.get('keyfile') - certfile = config.get('certfile') + keyfile = config.getstr('keyfile') + certfile = config.getstr('certfile') - device_id = config.get('device_id') + device_id = config.getstr('device_id') if not device_id: rng = random.SystemRandom() device_id = base64.urlsafe_b64encode( rng.getrandbits(24).to_bytes(3, 'little')).decode('ascii') config.set_and_save('device_id', device_id) - if config.get('jid'): + if config.getstr('jid'): # Field used to know if we are anonymous or not. # many features will be handled differently # depending on this setting self.anon = False - jid = config.get('jid') - password = config.get('password') - eval_password = config.get('eval_password') + jid = config.getstr('jid') + password = config.getstr('password') + eval_password = config.getstr('eval_password') if not password and not eval_password and not (keyfile and certfile): password = getpass.getpass() @@ -79,7 +79,7 @@ class Connection(slixmpp.ClientXMPP): '\n') else: # anonymous auth self.anon = True - jid = config.get('server') + jid = config.getstr('server') password = None try: jid = JID(jid) @@ -91,17 +91,17 @@ class Connection(slixmpp.ClientXMPP): 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')) + self, jid, password, lang=config.getstr('lang')) - force_encryption = config.get('force_encryption') + force_encryption = config.getbool('force_encryption') if force_encryption: self['feature_mechanisms'].unencrypted_plain = False self['feature_mechanisms'].unencrypted_digest = False self['feature_mechanisms'].unencrypted_cram = False self['feature_mechanisms'].unencrypted_scram = False - self.keyfile = config.get('keyfile') - self.certfile = config.get('certfile') + self.keyfile = keyfile + self.certfile = certfile if keyfile and not certfile: log.error( 'keyfile is present in configuration file without certfile') @@ -110,15 +110,15 @@ class Connection(slixmpp.ClientXMPP): 'certfile is present in configuration file without keyfile') self.core = None - self.auto_reconnect = config.get('auto_reconnect') + self.auto_reconnect = config.getbool('auto_reconnect') 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( + self.ciphers = config.getstr( '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') + self.ca_certs = config.getstr('ca_cert_path') or None + interval = config.getint('whitespace_interval') if int(interval) > 0: self.whitespace_keepalive_interval = int(interval) else: @@ -156,21 +156,21 @@ class Connection(slixmpp.ClientXMPP): # without a body XEP_0184._filter_add_receipt_request = fixes._filter_add_receipt_request self.register_plugin('xep_0184') - self.plugin['xep_0184'].auto_ack = config.get('ack_message_receipts') - self.plugin['xep_0184'].auto_request = config.get( + self.plugin['xep_0184'].auto_ack = config.getbool('ack_message_receipts') + self.plugin['xep_0184'].auto_request = config.getbool( 'request_message_receipts') self.register_plugin('xep_0191') - if config.get('enable_smacks'): + if config.getbool('enable_smacks'): self.register_plugin('xep_0198') self.register_plugin('xep_0199') - if config.get('enable_user_nick'): + if config.getbool('enable_user_nick'): self.register_plugin('xep_0172') - if config.get('send_poezio_info'): + if config.getbool('send_poezio_info'): info = {'name': 'poezio', 'version': options.custom_version} - if config.get('send_os_info'): + if config.getbool('send_os_info'): info['os'] = common.get_os_info() self.plugin['xep_0030'].set_identities(identities={('client', 'console', @@ -182,7 +182,7 @@ class Connection(slixmpp.ClientXMPP): 'console', None, '')}) self.register_plugin('xep_0092', pconfig=info) - if config.get('send_time'): + if config.getbool('send_time'): self.register_plugin('xep_0202') self.register_plugin('xep_0224') self.register_plugin('xep_0231') @@ -216,8 +216,8 @@ class Connection(slixmpp.ClientXMPP): # Happens when we change the value with /set while we are not # connected. Do nothing in that case return - ping_interval = config.get('connection_check_interval') - timeout_delay = config.get('connection_timeout_delay') + ping_interval = config.getint('connection_check_interval') + timeout_delay = config.getint('connection_timeout_delay') if timeout_delay <= 0: # We help the stupid user (with a delay of 0, poezio will try to # reconnect immediately because the timeout is immediately @@ -234,7 +234,7 @@ class Connection(slixmpp.ClientXMPP): """ Connect and process events. """ - custom_host = config.get('custom_host') + custom_host = config.getstr('custom_host') custom_port = config.get('custom_port', 5222) if custom_port == -1: custom_port = 5222 diff --git a/poezio/core/commands.py b/poezio/core/commands.py index d07c2e1e..3cd65207 100644 --- a/poezio/core/commands.py +++ b/poezio/core/commands.py @@ -424,8 +424,8 @@ class CommandCore: tab.password = password tab.join() - if config.get('synchronise_open_rooms') and room not in self.core.bookmarks: - method = 'remote' if config.get( + if config.getbool('synchronise_open_rooms') and room not in self.core.bookmarks: + method = 'remote' if config.getbool( 'use_remote_bookmarks') else 'local' await self._add_bookmark( room=room, @@ -472,7 +472,7 @@ class CommandCore: room, nick = self._parse_join_jid(args[0] if args else '') password = args[2] if len(args) > 2 else None - method = 'remote' if config.get('use_remote_bookmarks') else 'local' + method = 'remote' if config.getbool('use_remote_bookmarks') else 'local' autojoin = (method == 'local' or (len(args) > 1 and args[1].lower() == 'true')) diff --git a/poezio/core/completions.py b/poezio/core/completions.py index 88ed57b3..9b218c9a 100644 --- a/poezio/core/completions.py +++ b/poezio/core/completions.py @@ -82,7 +82,7 @@ class CompletionCore: def theme(self, the_input): """ Completion for /theme""" - themes_dir = config.get('themes_dir') + themes_dir = config.getstr('themes_dir') themes_dir = Path(themes_dir).expanduser( ) if themes_dir else xdg.DATA_HOME / 'themes' try: @@ -220,7 +220,7 @@ class CompletionCore: nicks = [tab.own_nick] if tab else [] default = os.environ.get('USER') if os.environ.get( 'USER') else 'poezio' - nick = config.get('default_nick') + nick = config.getstr('default_nick') if not nick: if default not in nicks: nicks.append(default) @@ -436,7 +436,7 @@ class CompletionCore: nicks = [tab.own_nick] if tab else [] default = os.environ.get('USER') if os.environ.get( 'USER') else 'poezio' - nick = config.get('default_nick') + nick = config.getstr('default_nick') if not nick: if default not in nicks: nicks.append(default) diff --git a/poezio/core/core.py b/poezio/core/core.py index 6372dd3e..93ea5c5b 100644 --- a/poezio/core/core.py +++ b/poezio/core/core.py @@ -95,9 +95,9 @@ class Core: self.connection_time = time.time() self.last_stream_error = None self.stdscr = None - status = config.get('status') + status = config.getstr('status') status = POSSIBLE_SHOW.get(status, None) - self.status = Status(show=status, message=config.get('status_message')) + self.status = Status(show=status, message=config.getstr('status_message')) self.running = True self.xmpp = connection.Connection() self.xmpp.core = self @@ -115,7 +115,7 @@ class Core: self.information_buffer = TextBuffer() self.information_win_size = cast( int, - config.get('info_win_height', section='var'), + config.getint('info_win_height', section='var'), ) self.information_win = windows.TextWin(300) self.information_buffer.add_window(self.information_win) @@ -134,10 +134,10 @@ class Core: self.tabs = Tabs(self.events) self.previous_tab_nb = 0 - own_nick = config.get('default_nick') + own_nick = config.getstr('default_nick') own_nick = own_nick or self.xmpp.boundjid.user own_nick = own_nick or os.environ.get('USER') - own_nick = own_nick or 'poezio' + own_nick = own_nick or 'poezio_user' self.own_nick = own_nick self.size = SizeManager(self) @@ -292,12 +292,12 @@ class Core: for name, handler in xmpp_event_handlers: self.xmpp.add_event_handler(name, handler) - if config.get('enable_avatars'): + if config.getbool('enable_avatars'): self.xmpp.add_event_handler("vcard_avatar_update", self.handler.on_vcard_avatar) self.xmpp.add_event_handler("avatar_metadata_publish", self.handler.on_0084_avatar) - if config.get('enable_user_nick'): + if config.getbool('enable_user_nick'): self.xmpp.add_event_handler("user_nick_publish", self.handler.on_nick_received) all_stanzas = Callback('custom matcher', connection.MatchAll(None), @@ -513,7 +513,7 @@ class Core: """ Load the plugins on startup. """ - plugins = config.get('plugins_autoload') + plugins = config.getstr('plugins_autoload') if ':' in plugins: for plugin in plugins.split(':'): self.plugin_manager.load(plugin, unload_first=False) @@ -609,7 +609,7 @@ class Core: except ValueError: pass else: - if self.tabs.current_tab.nb == nb and config.get( + if self.tabs.current_tab.nb == nb and config.getbool( 'go_to_previous_tab_on_alt_number'): self.go_to_previous_tab() else: @@ -722,9 +722,9 @@ class Core: work. If you try to do anything else, your |, [, <<, etc will be interpreted as normal command arguments, not shell special tokens. """ - if config.get('exec_remote'): + if config.getbool('exec_remote'): # We just write the command in the fifo - fifo_path = config.get('remote_fifo_path') + fifo_path = config.getstr('remote_fifo_path') filename = os.path.join(fifo_path, 'poezio.fifo') if not self.remote_fifo: try: @@ -818,7 +818,7 @@ class Core: or to use it when joining a new muc) """ self.status = Status(show=pres, message=msg) - if config.get('save_status'): + if config.getbool('save_status'): ok = config.silent_set('status', pres if pres else '') msg = msg.replace('\n', '|') if msg else '' ok = ok and config.silent_set('status_message', msg) @@ -1040,7 +1040,7 @@ class Core: returns False if it could not move the tab, True otherwise """ return self.tabs.insert_tab(old_pos, new_pos, - config.get('create_gaps')) + config.getbool('create_gaps')) ### Move actions (e.g. go to next room) ### @@ -1308,7 +1308,7 @@ class Core: tab.on_close() del tab.key_func # Remove self references del tab.commands # and make the object collectable - self.tabs.delete(tab, gap=config.get('create_gaps')) + self.tabs.delete(tab, gap=config.getbool('create_gaps')) logger.close(tab.name) if was_current: self.tabs.current_tab.on_gain_focus() @@ -1342,13 +1342,13 @@ class Core: """ Displays an informational message in the "Info" buffer """ - filter_types = config.get('information_buffer_type_filter').split(':') + filter_types = config.getlist('information_buffer_type_filter') 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) return False - filter_messages = config.get('filter_info_messages').split(':') + filter_messages = config.getlist('filter_info_messages') for words in filter_messages: if words and words in msg: log.debug( @@ -1364,11 +1364,11 @@ class Core: nick_color=color ) ) - popup_on = config.get('information_buffer_popup_on').split() + popup_on = config.getlist('information_buffer_popup_on') if isinstance(self.tabs.current_tab, tabs.RosterInfoTab): self.refresh_window() elif typ != '' and typ.lower() in popup_on: - popup_time = config.get('popup_time') + (nb_lines - 1) * 2 + popup_time = config.getint('popup_time') + (nb_lines - 1) * 2 self._pop_information_win_up(nb_lines, popup_time) else: if self.information_win_size != 0: @@ -1553,7 +1553,7 @@ class Core: """ Enable/disable the left panel. """ - enabled = config.get('enable_vertical_tab_list') + enabled = config.getbool('enable_vertical_tab_list') if not config.silent_set('enable_vertical_tab_list', str(not enabled)): self.information('Unable to write in the config file', 'Error') self.call_for_resize() @@ -1576,14 +1576,14 @@ class Core: Resize the GlobalInfoBar only once at each resize """ height, width = self.stdscr.getmaxyx() - if config.get('enable_vertical_tab_list'): + if config.getbool('enable_vertical_tab_list'): if self.size.core_degrade_x: return try: height, _ = self.stdscr.getmaxyx() truncated_win = self.stdscr.subwin( - height, config.get('vertical_tab_list_size'), 0, 0) + height, config.getint('vertical_tab_list_size'), 0, 0) except: log.error('Curses error on infobar resize', exc_info=True) return @@ -1609,11 +1609,13 @@ class Core: # the screen that they can occupy, and we draw the tab list on the # remaining space, on the left height, width = self.stdscr.getmaxyx() - if (config.get('enable_vertical_tab_list') + if (config.getbool('enable_vertical_tab_list') and not self.size.core_degrade_x): try: - scr = self.stdscr.subwin(0, - config.get('vertical_tab_list_size')) + scr = self.stdscr.subwin( + 0, + config.getint('vertical_tab_list_size') + ) except: log.error('Curses error on resize', exc_info=True) return @@ -1623,7 +1625,7 @@ class Core: self.resize_global_info_bar() self.resize_global_information_win() for tab in self.tabs: - if config.get('lazy_resize'): + if config.getbool('lazy_resize'): tab.need_resize = True else: tab.resize() @@ -1691,7 +1693,7 @@ class Core: def join_initial_rooms(self, bookmarks: List[Bookmark]): """Join all rooms given in the iterator `bookmarks`""" for bm in bookmarks: - if not (bm.autojoin or config.get('open_all_bookmarks')): + if not (bm.autojoin or config.getbool('open_all_bookmarks')): continue tab = self.tabs.by_name_and_class(bm.jid, tabs.MucTab) nick = bm.nick if bm.nick else self.own_nick @@ -1710,7 +1712,7 @@ class Core: self.bookmarks.available_storage['private'] = private self.bookmarks.available_storage['pep'] = pep_ - if not self.xmpp.anon and config.get('use_remote_bookmarks'): + if not self.xmpp.anon and config.getbool('use_remote_bookmarks'): try: await self.bookmarks.get_remote(self.xmpp, self.information) except IqError as error: @@ -1746,9 +1748,9 @@ class Core: msg = 'To provide a password in order to join the room, type "/join / password" (replace "password" by the real password)' tab.add_message(InfoMessage(msg), typ=2) if code == '409': - if config.get('alternative_nickname') != '': + if config.getstr('alternative_nickname') != '': if not tab.joined: - tab.own_nick += config.get('alternative_nickname') + tab.own_nick += config.getstr('alternative_nickname') tab.join() else: if not tab.joined: diff --git a/poezio/core/handlers.py b/poezio/core/handlers.py index ec714915..5fffbef8 100644 --- a/poezio/core/handlers.py +++ b/poezio/core/handlers.py @@ -94,7 +94,7 @@ class HandlerCore: rostertab.check_saslexternal(features) rostertab.check_blocking(features) self.core.check_blocking(features) - if (config.get('enable_carbons') + if (config.getbool('enable_carbons') and 'urn:xmpp:carbons:2' in features): self.core.xmpp.plugin['xep_0280'].enable() await self.core.check_bookmark_storage(features) @@ -230,7 +230,7 @@ class HandlerCore: if password: msg += ". The password is \"%s\"." % password self.core.information(msg, 'Info') - if 'invite' in config.get('beep_on').split(): + if 'invite' in config.getlist('beep_on'): curses.beep() logger.log_roster_change(inviter.full, 'invited you to %s' % jid.full) self.core.pending_invites[jid.bare] = inviter.full @@ -261,7 +261,7 @@ class HandlerCore: msg += "\nreason: %s" % reason self.core.information(msg, 'Info') - if 'invite' in config.get('beep_on').split(): + if 'invite' in config.getlist('beep_on'): curses.beep() self.core.pending_invites[room.bare] = inviter.full @@ -353,7 +353,7 @@ class HandlerCore: if conv_jid.bare in roster: remote_nick = roster[conv_jid.bare].name # check for a received nick - if not remote_nick and config.get('enable_user_nick'): + if not remote_nick and config.getbool('enable_user_nick'): if message.xml.find( '{http://jabber.org/protocol/nick}nick') is not None: remote_nick = message['nick']['nick'] @@ -425,7 +425,7 @@ class HandlerCore: typ=1, ) - if not own and 'private' in config.get('beep_on').split(): + if not own and 'private' in config.getlist('beep_on'): if not config.get_by_tabname('disable_beep', conv_jid.bare): curses.beep() if self.core.tabs.current_tab is not conversation: @@ -646,7 +646,7 @@ class HandlerCore: current.input.refresh() self.core.doupdate() - if 'message' in config.get('beep_on').split(): + if 'message' in config.getlist('beep_on'): if (not config.get_by_tabname('disable_beep', room_from) and self.core.own_nick != message['from'].resource): curses.beep() @@ -731,7 +731,7 @@ class HandlerCore: else: tab.last_remote_message = datetime.now() - if not sent and 'private' in config.get('beep_on').split(): + if not sent and 'private' in config.getlist('beep_on'): if not config.get_by_tabname('disable_beep', jid.full): curses.beep() if tab is self.core.tabs.current_tab: @@ -1095,14 +1095,14 @@ class HandlerCore: """ When we are disconnected from remote server """ - if 'disconnect' in config.get('beep_on').split(): + if 'disconnect' in config.getlist('beep_on'): curses.beep() # Stop the ping plugin. It would try to send stanza on regular basis self.core.xmpp.plugin['xep_0199'].disable_keepalive() msg_typ = 'Error' if not self.core.legitimate_disconnect else 'Info' self.core.information("Disconnected from server%s." % (event and ": %s" % event or ""), msg_typ) - if self.core.legitimate_disconnect or not config.get( - 'auto_reconnect', True): + if self.core.legitimate_disconnect or not config.getbool( + 'auto_reconnect'): return if (self.core.last_stream_error and self.core.last_stream_error[1]['condition'] in ( @@ -1166,7 +1166,7 @@ class HandlerCore: self.core.xmpp.get_roster() roster.update_contact_groups(self.core.xmpp.boundjid.bare) # send initial presence - if config.get('send_initial_presence'): + if config.getbool('send_initial_presence'): pres = self.core.xmpp.make_presence() pres['show'] = self.core.status.show pres['status'] = self.core.status.message @@ -1176,7 +1176,7 @@ class HandlerCore: # join all the available bookmarks. As of yet, this is just the local ones self.core.join_initial_rooms(self.core.bookmarks.local()) - if config.get('enable_user_nick'): + if config.getbool('enable_user_nick'): self.core.xmpp.plugin['xep_0172'].publish_nick( nick=self.core.own_nick, callback=dumb_callback) asyncio.ensure_future(self.core.xmpp.plugin['xep_0115'].update_caps()) @@ -1464,9 +1464,9 @@ class HandlerCore: """ Check the server certificate using the slixmpp ssl_cert event """ - if config.get('ignore_certificate'): + if config.getbool('ignore_certificate'): return - cert = config.get('certificate') + cert = config.getstr('certificate') # update the cert representation when it uses the old one if cert and ':' not in cert: cert = ':'.join( @@ -1608,7 +1608,7 @@ def _composing_tab_state(tab, state): else: return # should not happen - show = config.get('show_composing_tabs').lower() + show = config.getstr('show_composing_tabs').lower() show = show in values if tab.state != 'composing' and state == 'composing': diff --git a/poezio/plugin_e2ee.py b/poezio/plugin_e2ee.py index a0856957..de6a24c0 100644 --- a/poezio/plugin_e2ee.py +++ b/poezio/plugin_e2ee.py @@ -204,7 +204,7 @@ class E2EEPlugin(BasePlugin): def __load_encrypted_states(self) -> None: """Load previously stored encryption states for jids.""" for section in config.sections(): - value = config.get('encryption', section=section) + value = config.getstr('encryption', section=section) if value and value == self.encryption_short_name: self._enabled_tabs[section] = self.encrypt @@ -496,7 +496,7 @@ class E2EEPlugin(BasePlugin): def fetch_trust(self, jid: JID, fingerprint: str) -> str: """Fetch trust of a fingerprint and a jid.""" option_name = '%s:%s' % (self.encryption_short_name, fingerprint) - return config.get(option=option_name, section=jid) + return config.getstr(option=option_name, section=jid) async def decrypt(self, message: Message, jid: Optional[JID], tab: ChatTab): """Decryption method diff --git a/poezio/plugin_manager.py b/poezio/plugin_manager.py index bf708089..17673a9e 100644 --- a/poezio/plugin_manager.py +++ b/poezio/plugin_manager.py @@ -393,7 +393,7 @@ class PluginManager: """ Create the plugins_conf_dir """ - plugins_conf_dir = config.get('plugins_conf_dir') + plugins_conf_dir = config.getstr('plugins_conf_dir') self.plugins_conf_dir = Path(plugins_conf_dir).expanduser( ) if plugins_conf_dir else xdg.CONFIG_HOME / 'plugins' self.check_create_plugins_conf_dir() @@ -418,7 +418,7 @@ class PluginManager: """ Set the plugins_dir on start """ - plugins_dir = config.get('plugins_dir') + plugins_dir = config.getstr('plugins_dir') self.plugins_dir = Path(plugins_dir).expanduser( ) if plugins_dir else xdg.DATA_HOME / 'plugins' self.check_create_plugins_dir() diff --git a/poezio/roster.py b/poezio/roster.py index 4a6350a9..86fc704c 100644 --- a/poezio/roster.py +++ b/poezio/roster.py @@ -57,7 +57,8 @@ class Roster: # on search, for example self.contact_filter = self.DEFAULT_FILTER self.folded_groups = set( - config.get('folded_roster_groups', section='var').split(':')) + config.getlist('folded_roster_groups', section='var') + ) self.groups = {} self.contacts = {} self.length = 0 diff --git a/poezio/tabs/basetabs.py b/poezio/tabs/basetabs.py index 4aa6a370..7e584a92 100644 --- a/poezio/tabs/basetabs.py +++ b/poezio/tabs/basetabs.py @@ -143,7 +143,7 @@ class Tab: Returns 1 or 0, depending on if we are using the vertical tab list or not. """ - if config.get('enable_vertical_tab_list'): + if config.getbool('enable_vertical_tab_list'): return 0 return 1 @@ -332,7 +332,7 @@ class Tab: return False def refresh_tab_win(self) -> None: - if config.get('enable_vertical_tab_list'): + if config.getbool('enable_vertical_tab_list'): left_tab_win = self.core.left_tab_win if left_tab_win and not self.size.core_degrade_x: left_tab_win.refresh() @@ -621,7 +621,7 @@ class ChatTab(Tab): for word in txt.split(): if len(word) >= 4 and word not in words: words.append(word) - words.extend([word for word in config.get('words').split(':') if word]) + words.extend([word for word in config.getlist('words') if word]) self.input.auto_completion(words, ' ', quotify=False) def on_enter(self): @@ -800,8 +800,8 @@ class ChatTab(Tab): text_buffer = self._text_buffer built_lines = [] message_count = 0 - timestamp = config.get('show_timestamps') - nick_size = config.get('max_nick_length') + timestamp = config.getbool('show_timestamps') + nick_size = config.getint('max_nick_length') theme = get_theme() for message in text_buffer.messages: # Build lines of a message diff --git a/poezio/tabs/muctab.py b/poezio/tabs/muctab.py index c7d7d621..188ed156 100644 --- a/poezio/tabs/muctab.py +++ b/poezio/tabs/muctab.py @@ -433,7 +433,7 @@ class MucTab(ChatTab): return False def get_nick(self) -> str: - if config.get('show_muc_jid'): + if config.getbool('show_muc_jid'): return cast(str, self.jid.bare) bookmark = self.core.bookmarks[self.jid.bare] if bookmark is not None and bookmark.name: @@ -463,7 +463,7 @@ class MucTab(ChatTab): def on_gain_focus(self) -> None: self.state = 'current' if (self.text_win.built_lines and self.text_win.built_lines[-1] is None - and not config.get('show_useless_separator')): + and not config.getbool('show_useless_separator')): self.text_win.remove_line_separator() curses.curs_set(1) if self.joined and config.get_by_tabname( @@ -1245,7 +1245,7 @@ class MucTab(ChatTab): Resize the whole window. i.e. all its sub-windows """ self.need_resize = False - if config.get('hide_user_list') or self.size.tab_degrade_x: + if config.getbool('hide_user_list') or self.size.tab_degrade_x: text_width = self.width else: text_width = (self.width // 10) * 9 @@ -1280,7 +1280,7 @@ class MucTab(ChatTab): if self.need_resize: self.resize() log.debug(' TAB Refresh: %s', self.__class__.__name__) - if config.get('hide_user_list') or self.size.tab_degrade_x: + if config.getbool('hide_user_list') or self.size.tab_degrade_x: display_user_list = False else: display_user_list = True @@ -1302,7 +1302,7 @@ class MucTab(ChatTab): def on_info_win_size_changed(self) -> None: if self.core.information_win_size >= self.height - 3: return - if config.get("hide_user_list"): + if config.getbool("hide_user_list"): text_width = self.width else: text_width = (self.width // 10) * 9 @@ -1356,7 +1356,7 @@ class MucTab(ChatTab): if highlighted and self.joined and not corrected: if self.state != 'current': self.state = 'highlight' - beep_on = cast(str, config.get('beep_on')).split() + beep_on = config.getlist('beep_on') if 'highlight' in beep_on and 'message' not in beep_on: if not config.get_by_tabname('disable_beep', self.jid.bare): curses.beep() @@ -1506,7 +1506,7 @@ class MucTab(ChatTab): /close [msg] """ self.leave_room(msg) - if config.get('synchronise_open_rooms'): + if config.getbool('synchronise_open_rooms'): if self.jid in self.core.bookmarks: self.core.bookmarks[self.jid].autojoin = False asyncio.ensure_future( @@ -1806,14 +1806,14 @@ class MucTab(ChatTab): for user in sorted(self.users, key=COMPARE_USERS_LAST_TALKED, reverse=True): if user.nick != self.own_nick: word_list.append(user.nick) - after = cast(str, config.get('after_completion')) + ' ' + after = config.getstr('after_completion') + ' ' 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: - if not config.get('add_space_after_completion'): + if not config.getbool('add_space_after_completion'): add_after = '' else: add_after = ' ' @@ -1850,7 +1850,7 @@ class MucTab(ChatTab): """Completion for /nick""" nicks_list = [ os.environ.get('USER'), - cast(str, config.get('default_nick')), + config.getstr('default_nick'), self.core.get_bookmark_nickname(self.jid.bare) ] nicks = [i for i in nicks_list if i] diff --git a/poezio/tabs/privatetab.py b/poezio/tabs/privatetab.py index 94a6ad34..9d782df8 100644 --- a/poezio/tabs/privatetab.py +++ b/poezio/tabs/privatetab.py @@ -127,7 +127,7 @@ class PrivateTab(OneToOneTab): 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] - after = config.get('after_completion') + ' ' + after = config.getstr('after_completion') + ' ' 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): diff --git a/poezio/tabs/rostertab.py b/poezio/tabs/rostertab.py index 5d2e148c..78843f92 100644 --- a/poezio/tabs/rostertab.py +++ b/poezio/tabs/rostertab.py @@ -517,7 +517,7 @@ class RosterInfoTab(Tab): args[0] ) self.core.information('Password updated', 'Account') - if config.get('password'): + if config.getstr('password'): config.silent_set('password', args[0]) except (IqError, IqTimeout): self.core.information('Unable to change the password', @@ -868,7 +868,7 @@ class RosterInfoTab(Tab): Show or hide offline contacts """ option = 'roster_show_offline' - value = config.get(option) + value = config.getbool(option) success = config.silent_set(option, str(not value)) roster.modified() if not success: diff --git a/poezio/text_buffer.py b/poezio/text_buffer.py index 89bae3a2..48ec1e21 100644 --- a/poezio/text_buffer.py +++ b/poezio/text_buffer.py @@ -63,7 +63,7 @@ class TextBuffer: def __init__(self, messages_nb_limit: Optional[int] = None) -> None: if messages_nb_limit is None: - messages_nb_limit = cast(int, config.get('max_messages_in_memory')) + messages_nb_limit = config.getint('max_messages_in_memory') self._messages_nb_limit: int = messages_nb_limit # Message objects self.messages: List[BaseMessage] = [] @@ -184,8 +184,8 @@ class TextBuffer: self.messages.pop(0) ret_val = 0 - show_timestamps = cast(bool, config.get('show_timestamps')) - nick_size = cast(int, config.get('max_nick_length')) + show_timestamps = config.getbool('show_timestamps') + nick_size = config.getbool('max_nick_length') for window in self._windows: # make the associated windows # build the lines from the new message nb = window.build_new_message( diff --git a/poezio/theming.py b/poezio/theming.py index 6245a48d..e1d7ec87 100755 --- a/poezio/theming.py +++ b/poezio/theming.py @@ -507,7 +507,7 @@ def update_themes_dir(option: Optional[str] = None, load_path.append(default_dir) # import from the user-defined prefs - themes_dir_str = config.get('themes_dir') + themes_dir_str = config.getstr('themes_dir') themes_dir = Path(themes_dir_str).expanduser( ) if themes_dir_str else xdg.DATA_HOME / 'themes' try: @@ -553,7 +553,7 @@ def prepare_ccolor_palette(theme: Theme) -> None: def reload_theme() -> Optional[str]: - theme_name = config.get('theme') + theme_name = config.getstr('theme') global theme if theme_name == 'default' or not theme_name.strip(): theme = Theme() diff --git a/poezio/windows/image.py b/poezio/windows/image.py index 79ecf7d9..3b29f326 100644 --- a/poezio/windows/image.py +++ b/poezio/windows/image.py @@ -71,7 +71,7 @@ class ImageWin(Win): def __init__(self) -> None: self._image: Optional[Image.Image] = None Win.__init__(self) - if config.get('image_use_half_blocks'): + if config.getbool('image_use_half_blocks'): self._display_avatar: Callable[[int, int], None] = self._display_avatar_half_blocks else: self._display_avatar = self._display_avatar_full_blocks diff --git a/poezio/windows/info_bar.py b/poezio/windows/info_bar.py index c53ed68a..8c2dd1a1 100644 --- a/poezio/windows/info_bar.py +++ b/poezio/windows/info_bar.py @@ -31,11 +31,11 @@ class GlobalInfoBar(Win): self.addstr(0, 0, "[", to_curses_attr(theme.COLOR_INFORMATION_BAR)) - show_names = config.get('show_tab_names') - show_nums = config.get('show_tab_numbers') - use_nicks = config.get('use_tab_nicks') - show_inactive = config.get('show_inactive_tabs') - unique_prefix_tab_names = config.get('unique_prefix_tab_names') + show_names = config.getboom('show_tab_names') + show_nums = config.getbool('show_tab_numbers') + use_nicks = config.getbool('use_tab_nicks') + show_inactive = config.getbool('show_inactive_tabs') + unique_prefix_tab_names = config.getbool('unique_prefix_tab_names') if unique_prefix_tab_names: unique_prefixes = [None] * len(self.core.tabs) @@ -110,13 +110,13 @@ class VerticalGlobalInfoBar(Win): self._win.erase() sorted_tabs = [tab for tab in self.core.tabs if tab] theme = get_theme() - if not config.get('show_inactive_tabs'): + if not config.getbool('show_inactive_tabs'): sorted_tabs = [ tab for tab in sorted_tabs if tab.vertical_color != theme.COLOR_VERTICAL_TAB_NORMAL ] nb_tabs = len(sorted_tabs) - use_nicks = config.get('use_tab_nicks') + use_nicks = config.getbool('use_tab_nicks') if nb_tabs >= height: # TODO: As sorted_tabs filters out gap tabs this ensures pos is # always set, preventing UnboundLocalError. Now is this how this @@ -133,7 +133,7 @@ class VerticalGlobalInfoBar(Win): sorted_tabs = sorted_tabs[-height:] else: sorted_tabs = sorted_tabs[pos - height // 2:pos + height // 2] - asc_sort = (config.get('vertical_tab_list_sort') == 'asc') + asc_sort = (config.getstr('vertical_tab_list_sort') == 'asc') for y, tab in enumerate(sorted_tabs): color = tab.vertical_color if asc_sort: diff --git a/poezio/windows/info_wins.py b/poezio/windows/info_wins.py index cd775e33..5278e3b8 100644 --- a/poezio/windows/info_wins.py +++ b/poezio/windows/info_wins.py @@ -172,7 +172,7 @@ class ConversationInfoWin(InfoWin): # resource can now be a Resource: user is in the roster and online # or resource is None: user is in the roster but offline self._win.erase() - if config.get('show_jid_in_conversations'): + if config.getbool('show_jid_in_conversations'): self.write_contact_jid(jid) self.write_contact_information(contact) self.write_resource_information(resource) diff --git a/poezio/windows/inputs.py b/poezio/windows/inputs.py index b3601913..16c5c633 100644 --- a/poezio/windows/inputs.py +++ b/poezio/windows/inputs.py @@ -601,7 +601,7 @@ class HistoryInput(Input): self.current_completed = '' self.key_func['^R'] = self.toggle_search self.search = False - if config.get('separate_history'): + if config.getbool('separate_history'): # pylint: disable=assigning-non-slot self.history: List[str] = [] diff --git a/poezio/windows/muc.py b/poezio/windows/muc.py index 05fe683e..0e95ac1b 100644 --- a/poezio/windows/muc.py +++ b/poezio/windows/muc.py @@ -65,14 +65,14 @@ class UserList(Win): def refresh(self, users: List[User]) -> None: log.debug('Refresh: %s', self.__class__.__name__) - if config.get('hide_user_list'): + if config.getbool('hide_user_list'): return # do not refresh if this win is hidden. if len(users) < self.height: self.pos = 0 elif self.pos >= len(users) - self.height and self.pos != 0: self.pos = len(users) - self.height self._win.erase() - asc_sort = (config.get('user_list_sort').lower() == 'asc') + asc_sort = (config.getstr('user_list_sort').lower() == 'asc') if asc_sort: y, _ = self._win.getmaxyx() y -= 1 diff --git a/poezio/windows/roster_win.py b/poezio/windows/roster_win.py index 74de7eef..1db86630 100644 --- a/poezio/windows/roster_win.py +++ b/poezio/windows/roster_win.py @@ -99,13 +99,13 @@ class RosterWin(Win): # This is a search if roster.contact_filter is not roster.DEFAULT_FILTER: self.roster_cache = [] - sort = config.get('roster_sort', 'jid:show') or 'jid:show' + sort = config.getstr('roster_sort') or 'jid:show' for contact in roster.get_contacts_sorted_filtered(sort): self.roster_cache.append(contact) else: - show_offline = config.get('roster_show_offline') - sort = config.get('roster_sort') or 'jid:show' - group_sort = config.get('roster_group_sort') or 'name' + show_offline = config.getbool('roster_show_offline') + sort = config.getstr('roster_sort') or 'jid:show' + group_sort = config.getstr('roster_group_sort') or 'name' self.roster_cache = [] # build the cache for group in roster.get_groups(group_sort): @@ -155,9 +155,9 @@ class RosterWin(Win): self.height] options = { - 'show_roster_sub': config.get('show_roster_subscriptions'), - 'show_s2s_errors': config.get('show_s2s_errors'), - 'show_roster_jids': config.get('show_roster_jids') + 'show_roster_sub': config.getbool('show_roster_subscriptions'), + 'show_s2s_errors': config.getbool('show_s2s_errors'), + 'show_roster_jids': config.getbool('show_roster_jids') } for item in roster_view: diff --git a/poezio/windows/text_win.py b/poezio/windows/text_win.py index ac60dee7..2ddf7082 100644 --- a/poezio/windows/text_win.py +++ b/poezio/windows/text_win.py @@ -29,7 +29,7 @@ class TextWin(Win): def __init__(self, lines_nb_limit: Optional[int] = None) -> None: Win.__init__(self) if lines_nb_limit is None: - lines_nb_limit = config.get('max_lines_in_memory') + lines_nb_limit = config.getint('max_lines_in_memory') self.lines_nb_limit: int = lines_nb_limit self.pos = 0 # Each new message is built and kept here. @@ -119,8 +119,8 @@ class TextWin(Win): lines = self.built_lines[-self.height:] else: lines = self.built_lines[-self.height - self.pos:-self.pos] - with_timestamps = config.get("show_timestamps") - nick_size = config.get("max_nick_length") + with_timestamps = config.getbool("show_timestamps") + nick_size = config.getint("max_nick_length") self._win.move(0, 0) self._win.erase() offset = 0 @@ -167,8 +167,8 @@ class TextWin(Win): def rebuild_everything(self, room: TextBuffer) -> None: self.built_lines = [] - with_timestamps = config.get('show_timestamps') - nick_size = config.get('max_nick_length') + with_timestamps = config.getbool('show_timestamps') + nick_size = config.getint('max_nick_length') for message in room.messages: self.build_new_message( message, @@ -310,8 +310,8 @@ class TextWin(Win): Find a message, and replace it with a new one (instead of rebuilding everything in order to correct a message) """ - with_timestamps = config.get('show_timestamps') - nick_size = config.get('max_nick_length') + with_timestamps = config.getbool('show_timestamps') + nick_size = config.getint('max_nick_length') for i in range(len(self.built_lines) - 1, -1, -1): current = self.built_lines[i] if current is not None and current.msg.identifier == old_id: diff --git a/poezio/xhtml.py b/poezio/xhtml.py index ebbffb02..d8ea49a6 100644 --- a/poezio/xhtml.py +++ b/poezio/xhtml.py @@ -313,7 +313,7 @@ class XHTMLHandler(sax.ContentHandler): self.force_ns = force_ns self.tmp_image_dir = Path(tmp_image_dir) if tmp_image_dir else None - self.enable_css_parsing = config.get('enable_css_parsing') + self.enable_css_parsing = config.getbool('enable_css_parsing') @property def result(self) -> str: -- cgit v1.2.3