Commit e216fd21 authored by mathieui's avatar mathieui

Code cleanup

fixes whitespace issues, some builtin overrides, and some enormous lines

might make poezio run nanoseconds faster!
parent 218c71df
......@@ -11,13 +11,13 @@ bookmarks, both local and remote.
import logging
from sys import version_info
from sleekxmpp.plugins.xep_0048 import *
from sleekxmpp.plugins.xep_0048 import Bookmarks, Conference
from common import safeJID
from config import config
log = logging.getLogger(__name__)
def iter(xml, tag=''):
def xml_iter(xml, tag=''):
if version_info[1] >= 2:
return xml.iter(tag)
else:
......@@ -88,10 +88,10 @@ class Bookmark(object):
name = el.get('name')
autojoin = True if el.get('autojoin', 'false').lower() in ('true', '1') else False
nick = None
for n in iter(el, 'nick'):
nick = nick.text
for n in xml_iter(el, 'nick'):
nick = n.text
password = None
for p in iter(el, 'password'):
for p in xml_iter(el, 'password'):
password = p.text
return Bookmark(jid, name, autojoin, nick, password, method)
......@@ -117,7 +117,7 @@ def remove(value):
def stanza_storage(method):
"""Generate a <storage/> stanza with the conference elements."""
storage = Bookmarks()
for b in filter(lambda b: b.method == method, bookmarks):
for b in (b for bookmark in bookmark if b.method == method):
storage.append(b.stanza())
return storage
......@@ -142,16 +142,15 @@ def save_remote(xmpp, method=preferred):
else:
xmpp.plugin['xep_0048'].set_bookmarks(stanza_storage('pep'),
method='xep_0223')
except:
import traceback
log.error("Could not save the bookmarks:\n%s" % traceback.format_exc())
except Exception:
log.error("Could not save the bookmarks:", exc_info=True)
return False
return True
def save_local():
"""Save the local bookmarks."""
all = ''.join(bookmark.local() for bookmark in bookmarks if bookmark.method is 'local')
config.set_and_save('rooms', all)
local = ''.join(bookmark.local() for bookmark in bookmarks if bookmark.method is 'local')
config.set_and_save('rooms', local)
def save(xmpp, core=None):
"""Save all the bookmarks."""
......@@ -171,7 +170,7 @@ def get_pep(xmpp):
iq = xmpp.plugin['xep_0048'].get_bookmarks(method='xep_0223', block=True)
except:
return False
for conf in iter(iq.xml, '{storage:bookmarks}conference'):
for conf in xml_iter(iq.xml, '{storage:bookmarks}conference'):
b = Bookmark.parse_from_element(conf, method='pep')
if not get_by_jid(b.jid):
bookmarks.append(b)
......@@ -183,7 +182,7 @@ def get_privatexml(xmpp):
iq = xmpp.plugin['xep_0048'].get_bookmarks(method='xep_0049', block=True)
except:
return False
for conf in iter(iq.xml, '{storage:bookmarks}conference'):
for conf in xml_iter(iq.xml, '{storage:bookmarks}conference'):
b = Bookmark.parse_from_element(conf, method='privatexml')
if not get_by_jid(b.jid):
bookmarks.append(b)
......
......@@ -205,7 +205,7 @@ def datetime_tuple(timestamp):
tz_msg = timestamp[15:]
try:
ret = datetime.strptime(date, '%Y%m%dT%H%M%S')
except Exception as e:
except Exception:
ret = datetime.now()
# add the message timezone if any
try:
......@@ -215,7 +215,7 @@ def datetime_tuple(timestamp):
tz_msg = tz_msg.tm_hour * 3600 + tz_msg.tm_min * 60
tz_msg = timedelta(seconds=tz_mod * tz_msg)
ret -= tz_msg
except Exception as e:
except Exception:
pass # ignore if we got a badly-formatted offset
# convert UTC to local time, with DST etc.
if time.daylight and time.localtime().tm_isdst:
......
......@@ -143,9 +143,6 @@ class Config(RawConfigParser):
Our own way to save write the value in the file
Just find the right section, and then find the
right option, and edit it.
TODO: make it write also new values in the file, not just what did already
exist
"""
if path.exists(self.file_name):
df = open(self.file_name, 'r', encoding='utf-8')
......
......@@ -105,10 +105,12 @@ class Connection(sleekxmpp.ClientXMPP):
'version': options.version}
if config.get('send_os_info', True):
info['os'] = common.get_os_info()
self.plugin['xep_0030'].set_identities(identities=set([('client', 'pc', None,'Poezio')]))
self.plugin['xep_0030'].set_identities(
identities=set([('client', 'pc', None, 'Poezio')]))
else:
info = {'name': '', 'version': ''}
self.plugin['xep_0030'].set_identities(identities=set([('client', 'pc', None,'')]))
self.plugin['xep_0030'].set_identities(
identities=set([('client', 'pc', None, '')]))
self.register_plugin('xep_0092', pconfig=info)
if config.get('send_time', True):
self.register_plugin('xep_0202')
......
......@@ -175,7 +175,7 @@ class Core(object):
'_dnd': lambda: self.command_status('dnd'),
'_xa': lambda: self.command_status('xa'),
##### Custom actions ########
'_exc_': lambda arg: self.try_execute(arg),
'_exc_': self.try_execute,
}
self.key_func.update(key_func)
......@@ -193,8 +193,8 @@ class Core(object):
self.xmpp.add_event_handler("groupchat_config_status", self.on_status_codes)
self.xmpp.add_event_handler("groupchat_subject", self.on_groupchat_subject)
self.xmpp.add_event_handler("message", self.on_message)
self.xmpp.add_event_handler("got_online" , self.on_got_online)
self.xmpp.add_event_handler("got_offline" , self.on_got_offline)
self.xmpp.add_event_handler("got_online", self.on_got_online)
self.xmpp.add_event_handler("got_offline", self.on_got_offline)
self.xmpp.add_event_handler("roster_update", self.on_roster_update)
self.xmpp.add_event_handler("changed_status", self.on_presence)
self.xmpp.add_event_handler("presence_error", self.on_presence_error)
......@@ -429,7 +429,7 @@ class Core(object):
res = []
current = []
for char in char_list:
assert(len(char) > 0)
assert len(char) > 0
# Transform that stupid char into what we actually meant
if char == '\x1f':
char = '^/'
......@@ -859,7 +859,7 @@ class Core(object):
return False
elif new_pos <= 0:
return False
elif new_pos ==old_pos:
elif new_pos == old_pos:
return False
elif not self.tabs[old_pos]:
return False
......
......@@ -222,7 +222,7 @@ def on_nick_received(self, message):
if item.xml.find('{http://jabber.org/protocol/nick}nick'):
contact.name = item['nick']['nick']
else:
contact.name= ''
contact.name = ''
def on_gaming_event(self, message):
"""
......@@ -343,7 +343,7 @@ def on_tune_event(self, message):
old_tune = contact.tune
if item.xml.find('{http://jabber.org/protocol/tune}tune'):
item = item['tune']
contact.tune = {
contact.tune = {
'artist': item['artist'],
'length': item['length'],
'rating': item['rating'],
......@@ -812,9 +812,9 @@ def on_session_start(self, event):
self.initial_joins.append(bm.jid)
histo_length = config.get('muc_history_length', 20)
if histo_length == -1:
histo_length= None
histo_length = None
if histo_length is not None:
histo_length= str(histo_length)
histo_length = str(histo_length)
# do not join rooms that do not have autojoin
# but display them anyway
if bm.autojoin:
......@@ -845,7 +845,7 @@ def on_status_codes(self, message):
hide_unavailable = '103' in status_codes
non_priv = '104' in status_codes
logging_on = '170' in status_codes
logging_off= '171' in status_codes
logging_off = '171' in status_codes
non_anon = '172' in status_codes
semi_anon = '173' in status_codes
full_anon = '174' in status_codes
......
......@@ -50,22 +50,22 @@ class Executor(threading.Thread):
command.pop(-1)
def run(self):
log.info('executing %s' % (self.command,))
log.debug('executing %s', self.command)
stdout = None
if self.filename:
try:
stdout = open(self.filename, self.redirection_mode)
except (OSError, IOError) as e:
log.error('Could not open redirection file: %s (%s)' % (self.filename, e,))
except (OSError, IOError):
log.error('Could not open redirection file: %s', self.filename, exc_info=True)
return
try:
subprocess.call(self.command, stdout=stdout)
except:
import traceback
if self.remote:
import traceback
print(traceback.format_exc())
else:
log.error('Could not execute %s:\n%s', self.command, traceback.format_exc())
log.error('Could not execute %s:', self.command, exc_info=True)
def main():
while True:
......
......@@ -110,7 +110,6 @@ def get_char_list_new(s):
pass
except ValueError: # invalid input
log.debug('Invalid character entered.')
pass
else:
key = 'M-%s' % part
# and an even more special case for keys like
......@@ -123,7 +122,6 @@ def get_char_list_new(s):
pass
except ValueError:
log.debug('Invalid character entered.')
pass
else:
key = '%s-%s' % (key, part)
if key == '\x7f' or key == '\x08':
......
......@@ -91,7 +91,8 @@ def leave_groupchat(xmpp, jid, own_nick, msg):
try:
xmpp.plugin['xep_0045'].leaveMUC(jid, own_nick, msg)
except KeyError:
log.debug("muc.leave_groupchat: could not leave the room %s" % jid)
log.debug("muc.leave_groupchat: could not leave the room %s",
jid, exc_info=True)
def set_user_role(xmpp, jid, nick, reason, role, callback=None):
"""
......
......@@ -290,7 +290,7 @@ class PluginManager(object):
else:
self.core.xmpp.del_event_handler(event_name, handler)
eh = self.event_handlers[module_name]
eh = list(filter(lambda e : e != (event_name, handler), eh))
eh = list(filter(lambda e: e != (event_name, handler), eh))
def completion_load(self, the_input):
"""
......
......@@ -94,7 +94,7 @@ class shlex(object):
print("shlex: popping token " + repr(tok))
return tok
# No pushback. Get a token.
start, end, raw = self.read_token()
start, end, raw = self.read_token()
return start, end, raw
def read_token(self):
......
......@@ -76,8 +76,7 @@ class Roster(object):
self.__node[jid].send_presence(ptype='unavailable')
self.__node.remove(jid)
except (IqError, IqTimeout):
import traceback
log.debug('IqError when removing %s:\n%s', jid, traceback.format_exc())
log.debug('IqError when removing %s:', jid, exc_info=True)
def __delitem__(self, jid):
"""Remove a contact from the roster view"""
......@@ -120,10 +119,7 @@ class Roster(object):
def get_groups(self, sort=''):
"""Return a list of the RosterGroups"""
group_list = sorted(
filter(
lambda x: bool(x),
self.groups.values()
),
(group for group in self.groups.values() if group),
key=lambda x: x.name.lower() if x.name else ''
)
......@@ -189,7 +185,7 @@ class Roster(object):
"""
folded_groups = ':'.join([group.name for group in self.groups.values()\
if group.folded])
log.debug('folded:%s\n' %folded_groups)
log.debug('folded:%s\n', folded_groups)
return config.silent_set('folded_roster_groups', folded_groups, 'var')
def get_nb_connected_contacts(self):
......
......@@ -123,7 +123,7 @@ class MucListTab(Tab):
for item in substanza['substanzas']:
if isinstance(item, DiscoItem):
yield (item['jid'], item['node'], item['name'])
items = [ (item[0].split('@')[0],
items = [(item[0].split('@')[0],
item[0],
item[2] or '', '') for item in get_items()]
self.listview.set_lines(items)
......
......@@ -21,7 +21,8 @@ from theming import get_theme
message_fields = 'txt nick_color time str_time nickname user identifier highlight me old_message revisions jid'
Message = collections.namedtuple('Message', message_fields)
class CorrectionError(Exception): pass
class CorrectionError(Exception):
pass
def other_elems(self):
acc = ['Message(']
......@@ -29,16 +30,16 @@ def other_elems(self):
fields.remove('old_message')
for field in fields:
acc.append('%s=%s' % (field, repr(getattr(self, field))))
return (', '.join(acc) + ', old_message=')
return ', '.join(acc) + ', old_message='
def repr_message(self):
init = other_elems(self)
acc = [init]
next = self.old_message
next_message = self.old_message
rev = 1
while next:
acc.append(other_elems(next))
next = next.old_message
while next_message:
acc.append(other_elems(next_message))
next_message = next_message.old_message
rev += 1
acc.append('None')
while rev:
......@@ -69,7 +70,8 @@ class TextBuffer(object):
return self.messages[-1] if self.messages else None
def make_message(self, txt, time, nickname, nick_color, history, user, identifier, str_time=None, highlight=False, old_message=None, revisions=0, jid=None):
@staticmethod
def make_message(txt, time, nickname, nick_color, history, user, identifier, str_time=None, highlight=False, old_message=None, revisions=0, jid=None):
time = time or datetime.now()
me = False
if txt.startswith('/me '):
......
......@@ -226,7 +226,43 @@ class Theme(object):
# A list of colors randomly attributed to nicks in MUCs
# Setting more colors makes it harder to have two nicks with the same color,
# avoiding confusions.
LIST_COLOR_NICKNAMES = [(1, -1), (2, -1), (3, -1), (4, -1), (5, -1), (6, -1), (9, -1), (10, -1), (11, -1), (12, -1), (13, -1), (14, -1), (19, -1), (20, -1), (21, -1), (22, -1), (23, -1), (24, -1), (25, -1), (26, -1), (27, -1), (28, -1), (29, -1), (30, -1), (31, -1), (32, -1), (33, -1), (34, -1), (35, -1), (36, -1), (37, -1), (38, -1), (39, -1), (40, -1), (41, -1), (42, -1), (43, -1), (44, -1), (45, -1), (46, -1), (47, -1), (48, -1), (49, -1), (50, -1), (51, -1), (54, -1), (55, -1), (56, -1), (57, -1), (58, -1), (60, -1), (61, -1), (62, -1), (63, -1), (64, -1), (65, -1), (66, -1), (67, -1), (68, -1), (69, -1), (70, -1), (71, -1), (72, -1), (73, -1), (74, -1), (75, -1), (76, -1), (77, -1), (78, -1), (79, -1), (80, -1), (81, -1), (82, -1), (83, -1), (84, -1), (85, -1), (86, -1), (87, -1), (88, -1), (89, -1), (90, -1), (91, -1), (92, -1), (93, -1), (94, -1), (95, -1), (96, -1), (97, -1), (98, -1), (99, -1), (100, -1), (101, -1), (103, -1), (104, -1), (105, -1), (106, -1), (107, -1), (108, -1), (109, -1), (110, -1), (111, -1), (112, -1), (113, -1), (114, -1), (115, -1), (116, -1), (117, -1), (118, -1), (119, -1), (120, -1), (121, -1), (122, -1), (123, -1), (124, -1), (125, -1), (126, -1), (127, -1), (128, -1), (129, -1), (130, -1), (131, -1), (132, -1), (133, -1), (134, -1), (135, -1), (136, -1), (137, -1), (138, -1), (139, -1), (140, -1), (141, -1), (142, -1), (143, -1), (144, -1), (145, -1), (146, -1), (147, -1), (148, -1), (149, -1), (150, -1), (151, -1), (152, -1), (153, -1), (154, -1), (155, -1), (156, -1), (157, -1), (158, -1), (159, -1), (160, -1), (161, -1), (162, -1), (163, -1), (164, -1), (165, -1), (166, -1), (167, -1), (168, -1), (169, -1), (170, -1), (171, -1), (172, -1), (173, -1), (174, -1), (175, -1), (176, -1), (177, -1), (178, -1), (179, -1), (180, -1), (181, -1), (182, -1), (183, -1), (184, -1), (185, -1), (186, -1), (187, -1), (188, -1), (189, -1), (190, -1), (191, -1), (192, -1), (193, -1), (196, -1), (197, -1), (198, -1), (199, -1), (200, -1), (201, -1), (202, -1), (203, -1), (204, -1), (205, -1), (206, -1), (207, -1), (208, -1), (209, -1), (210, -1), (211, -1), (212, -1), (213, -1), (214, -1), (215, -1), (216, -1), (217, -1), (218, -1), (219, -1), (220, -1), (221, -1), (222, -1), (223, -1), (224, -1), (225, -1), (226, -1), (227, -1)]
LIST_COLOR_NICKNAMES = [
(1, -1), (2, -1), (3, -1), (4, -1), (5, -1), (6, -1), (9, -1),
(10, -1), (11, -1), (12, -1), (13, -1), (14, -1), (19, -1),
(20, -1), (21, -1), (22, -1), (23, -1), (24, -1), (25, -1),
(26, -1), (27, -1), (28, -1), (29, -1), (30, -1), (31, -1),
(32, -1), (33, -1), (34, -1), (35, -1), (36, -1), (37, -1),
(38, -1), (39, -1), (40, -1), (41, -1), (42, -1), (43, -1),
(44, -1), (45, -1), (46, -1), (47, -1), (48, -1), (49, -1),
(50, -1), (51, -1), (54, -1), (55, -1), (56, -1), (57, -1),
(58, -1), (60, -1), (61, -1), (62, -1), (63, -1), (64, -1),
(65, -1), (66, -1), (67, -1), (68, -1), (69, -1), (70, -1),
(71, -1), (72, -1), (73, -1), (74, -1), (75, -1), (76, -1),
(77, -1), (78, -1), (79, -1), (80, -1), (81, -1), (82, -1),
(83, -1), (84, -1), (85, -1), (86, -1), (87, -1), (88, -1),
(89, -1), (90, -1), (91, -1), (92, -1), (93, -1), (94, -1),
(95, -1), (96, -1), (97, -1), (98, -1), (99, -1), (100, -1),
(101, -1), (103, -1), (104, -1), (105, -1), (106, -1), (107, -1),
(108, -1), (109, -1), (110, -1), (111, -1), (112, -1), (113, -1),
(114, -1), (115, -1), (116, -1), (117, -1), (118, -1), (119, -1),
(120, -1), (121, -1), (122, -1), (123, -1), (124, -1), (125, -1),
(126, -1), (127, -1), (128, -1), (129, -1), (130, -1), (131, -1),
(132, -1), (133, -1), (134, -1), (135, -1), (136, -1), (137, -1),
(138, -1), (139, -1), (140, -1), (141, -1), (142, -1), (143, -1),
(144, -1), (145, -1), (146, -1), (147, -1), (148, -1), (149, -1),
(150, -1), (151, -1), (152, -1), (153, -1), (154, -1), (155, -1),
(156, -1), (157, -1), (158, -1), (159, -1), (160, -1), (161, -1),
(162, -1), (163, -1), (164, -1), (165, -1), (166, -1), (167, -1),
(168, -1), (169, -1), (170, -1), (171, -1), (172, -1), (173, -1),
(174, -1), (175, -1), (176, -1), (177, -1), (178, -1), (179, -1),
(180, -1), (181, -1), (182, -1), (183, -1), (184, -1), (185, -1),
(186, -1), (187, -1), (188, -1), (189, -1), (190, -1), (191, -1),
(192, -1), (193, -1), (196, -1), (197, -1), (198, -1), (199, -1),
(200, -1), (201, -1), (202, -1), (203, -1), (204, -1), (205, -1),
(206, -1), (207, -1), (208, -1), (209, -1), (210, -1), (211, -1),
(212, -1), (213, -1), (214, -1), (215, -1), (216, -1), (217, -1),
(218, -1), (219, -1), (220, -1), (221, -1), (222, -1), (223, -1),
(224, -1), (225, -1), (226, -1), (227, -1)]
# This is your own nickname
COLOR_OWN_NICK = (254, -1)
......@@ -474,9 +510,7 @@ def reload_theme():
update_themes_dir()
if __name__ == '__main__':
"""
Display some nice text with nice colors
"""
# Display some nice text with nice colors
s = curses.initscr()
curses.start_color()
curses.use_default_colors()
......
This diff is collapsed.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment