From e4e15e7f4e594efc899016ba17cabd02fa344600 Mon Sep 17 00:00:00 2001 From: Simeon Simeonov Date: Thu, 8 May 2014 10:25:39 +0200 Subject: Forcing PEP8 compatibility --- beinc_generic_client.py | 15 +--- beinc_server.py | 53 ++++--------- beinc_weechat.py | 202 +++++++++++++++++++++--------------------------- 3 files changed, 103 insertions(+), 167 deletions(-) diff --git a/beinc_generic_client.py b/beinc_generic_client.py index 6cffc84..39e0fe8 100755 --- a/beinc_generic_client.py +++ b/beinc_generic_client.py @@ -55,7 +55,6 @@ class ValidHTTPSConnection(httplib.HTTPConnection): cert_reqs=ssl.CERT_REQUIRED) - class ValidHTTPSHandler(urllib2.HTTPSHandler): """ Implements a simple CERT verification functionality @@ -65,7 +64,6 @@ class ValidHTTPSHandler(urllib2.HTTPSHandler): return self.do_open(ValidHTTPSConnection, req) - def action_push(args): """ """ @@ -90,66 +88,57 @@ def action_push(args): print('Body:\n{0}'.format(response.read())) response.close() except urllib2.HTTPError as e: - sys.stderr.write('BEINC-server error ({0} - {1})\n'.format(e.code, e.reason)) + sys.stderr.write('BEINC-server error ({0} - {1})\n'.format(e.code, + e.reason)) except Exception as e: sys.stderr.write('BEINC generic client error: {0}\n'.format(e)) sys.exit(errno.EPERM) def main(): - parser = argparse.ArgumentParser( description='The following options are available') - parser.add_argument('url', metavar='URL', type=str, #dest='url', #required=True, help='Destination URL') - parser.add_argument('-c', '--cert-file', metavar='FILE', type=str, dest='cert', default='', help='BEINC CA-cert to check the server-cert against') - parser.add_argument('-m', '--message', metavar='MESSAGE', type=str, dest='message', default='BEINC message', help='BEINC message') - parser.add_argument('-p', '--password', metavar='PASSWORD', type=str, dest='password', default='', help='Password') - parser.add_argument('-t', '--title', metavar='TITLE', type=str, dest='title', default='BEINC title', help='BEINC title') - parser.add_argument('-v', '--version', action='version', version='%(prog)s {0}'.format(__version__), help='display program-version and exit') - args = parser.parse_args() - if not args.password: try: args.password = getpass.getpass() except Exception as e: sys.stderr.write('Prompt terminated\n') sys.exit(errno.EACCES) - action_push(args) sys.exit(0) diff --git a/beinc_server.py b/beinc_server.py index d4dd3c3..05568b6 100755 --- a/beinc_server.py +++ b/beinc_server.py @@ -52,7 +52,6 @@ class BEINCInstance(object): """ instance_dict: the config-dictionary node that represents this instance """ - self.__message_queue = list() self.__osd_type = BEINC_OSD_TYPE_NONE self.__osd_notification = None @@ -60,7 +59,6 @@ class BEINCInstance(object): self.__name = instance_dict.get('name') self.__password = instance_dict.get('password', '') self.__queue_size = int(instance_dict.get('queue_size', 3)) - if instance_dict['osd_system'].lower() == 'pynotify': self.__queue_size = 0 # disable queueing if not pynotify: @@ -70,7 +68,6 @@ class BEINCInstance(object): 'Remove the instance {0}'.format(self.__name)) sys.stderr.write("or define it with 'osd_system': 'none'\n") sys.exit(errno.EPERM) - try: self.__osd_notification = pynotify.Notification(' ') self.__osd_notification.set_timeout( @@ -82,10 +79,8 @@ class BEINCInstance(object): sys.stderr.write( 'Unable to set up a notification object for {0} ({1})\n') sys.exit(errno.EPERM) - self.__osd_type = BEINC_OSD_TYPE_PYNOTIFY - @property def name(self): """ @@ -129,7 +124,6 @@ class BEINCInstance(object): """ Displays pynotify message """ - self.__osd_notification.set_properties(summary=title, body=message) self.__osd_notification.show() @@ -137,10 +131,8 @@ class BEINCInstance(object): """ Enqueues the message """ - if len(self.__message_queue) >= self.__queue_size: self.__message_queue.pop(0) - self.__message_queue.append({'title': title, 'message': message}) @@ -150,20 +142,16 @@ def beinc_instance_login(method): """ def wrapper(self, *args, **kwargs): - if not args: - raise cherrypy.HTTPError(status = 404) - + raise cherrypy.HTTPError(status=404) try: instance = self.instances[args[0]] except Exception as e: - raise cherrypy.HTTPError(status = 401, - message = 'Wrong instance or password') - + raise cherrypy.HTTPError(status=401, + message='Wrong instance or password') if not instance.password_match(kwargs.get('password')): - raise cherrypy.HTTPError(status = 401, - message = 'Wrong instance or password') - + raise cherrypy.HTTPError(status=401, + message='Wrong instance or password') return method(self, *args, **kwargs) return wrapper @@ -176,7 +164,6 @@ class WebNotifyServer(object): """ self.__config = config self.__instances = dict() - # initialize pynotify if the module exists and if needed if pynotify: for instance in self.__config['server']['instances']: @@ -191,14 +178,12 @@ class WebNotifyServer(object): for instance in self.__config['server']['instances']: self.__instances[instance['name']] = BEINCInstance(instance) print('Instance "{0}" added'.format(instance['name'])) - except Exception as e: sys.stderr.write('Unable to create instance "{0}": {1}\n'.format( instance['name'], e)) sys.exit(1) - @property def instances(self): return self.__instances @@ -217,14 +202,11 @@ class WebNotifyServer(object): """ return 'default' - @cherrypy.expose @beinc_instance_login def push(self, *args, **kwargs): - instance = self.__instances[args[0]] - - print('**kwargs: {0}'.format(str(kwargs))) + ##print('**kwargs: {0}'.format(str(kwargs))) title = kwargs.get('title', '') message = kwargs.get('message', '') try: @@ -237,18 +219,15 @@ class WebNotifyServer(object): e)) raise cherrypy.HTTPError(500, 'Unable to send message') - @cherrypy.expose @beinc_instance_login def pull(self, *args, **kwargs): - instance = self.__instances[args[0]] if not instance.queueable: raise cherrypy.HTTPError( - status = 405, - message = 'BEINC instance "{0}" does not support queuing'.format( + status=405, + message='BEINC instance "{0}" does not support queuing'.format( instance.name)) - return instance.get_queue() @@ -256,56 +235,51 @@ def main(): parser = argparse.ArgumentParser( description='The following options are available') - parser.add_argument('-d', action='store_true', dest='daemonize', default=False, help='daemonize the server process') - parser.add_argument('-H', '--hostname', metavar='HOSTNAME', type=str, dest='hostname', default='127.0.0.1', help="Server IP / hostname") - parser.add_argument('-p', '--port', metavar='PORT', type=int, dest='port', default=9998, help="Server port") - parser.add_argument('-c', '--config-file', metavar='FILE', type=str, default=os.path.expanduser('~/.beinc_server.json'), dest='config_file', help="config file") - parser.add_argument('-v', '--version', action='version', version='%(prog)s {0}'.format(__version__), help='display program-version and exit') - args = parser.parse_args() try: with open(args.config_file, 'r') as fp: config_dict = json.load(fp) - except Exception as e: sys.stderr.write('Unable to parse {0}: {1}'.format(args.config_file, e)) sys.exit(errno.EIO) + ssl_certificate = config_dict['server']['general']['ssl_certificate'] + ssl_private_key = config_dict['server']['general']['ssl_private_key'] cherrypy.config.update({ 'server.socket_host': args.hostname, 'server.socket_port': args.port, - 'server.ssl_module': config_dict['server']['general']['ssl_module'].encode('utf-8'), - 'server.ssl_certificate': config_dict['server']['general']['ssl_certificate'], - 'server.ssl_private_key': config_dict['server']['general']['ssl_private_key'], + 'server.ssl_module': config_dict['server']['general']['ssl_module'], + 'server.ssl_certificate': ssl_certificate, + 'server.ssl_private_key': ssl_private_key, 'tools.encode.on': True, 'tools.encode.encoding': 'utf-8', 'tools.log_tracebacks.on': False, @@ -314,7 +288,6 @@ def main(): try: cherrypy.quickstart(WebNotifyServer(config_dict)) - except Exception as e: sys.stderr.write("WebServer error: {0}".format(e)) sys.exit(1) diff --git a/beinc_weechat.py b/beinc_weechat.py index 8b4392f..8462b76 100644 --- a/beinc_weechat.py +++ b/beinc_weechat.py @@ -46,7 +46,6 @@ BEINC_POLICY_ALL = 1 BEINC_POLICY_LIST_ONLY = 2 - class ValidHTTPSConnection(httplib.HTTPConnection): """ Implements a simple CERT verification functionality @@ -68,7 +67,6 @@ class ValidHTTPSConnection(httplib.HTTPConnection): cert_reqs=ssl.CERT_REQUIRED) - class ValidHTTPSHandler(urllib2.HTTPSHandler): """ Implements a simple CERT verification functionality @@ -78,11 +76,10 @@ class ValidHTTPSHandler(urllib2.HTTPSHandler): return self.do_open(ValidHTTPSConnection, req) - class WeechatTarget(object): """ """ - + def __init__(self, target_dict): """ target_dict: the config-dictionary node that represents this instance @@ -92,22 +89,18 @@ class WeechatTarget(object): ''.join([chr(random.randrange(97, 123)) for x in range(4)])) self.__url = target_dict.get('target_url') self.__password = target_dict.get('target_password') - self.__pm_title_template = target_dict.get('pm_title_template', '%s @ %S') self.__pm_message_template = target_dict.get('pm_message_template', '%m') - self.__cm_title_template = target_dict.get('cm_title_template', '%c @ %S') self.__cm_message_template = target_dict.get('cm_message_template', '%s -> %m') - self.__nm_title_template = target_dict.get('nm_title_template', '%c @ %S') self.__nm_message_template = target_dict.get('nm_message_template', '%s -> %m') - self.__chans = set(target_dict.get('channel_list', list())) self.__nicks = set(target_dict.get('nick_list', list())) self.__chan_messages_policy = int(target_dict.get( @@ -125,62 +118,54 @@ class WeechatTarget(object): self.__debug = bool(target_dict.get('debug', False)) self.__enabled = bool(target_dict.get('enabled', True)) - @property def name(self): """ """ return self.__name - @property def chans(self): - """ - """ + """ + """ return self.__chans - - + @property def nicks(self): - """ - """ + """ + """ return self.__nicks - @property def channel_messages_policy(self): - """ - """ + """ + """ return self.__chan_messages_policy - @property def private_messages_policy(self): - """ - """ + """ + """ return self.__priv_messages_policy - @property def notifications_policy(self): - """ - """ + """ + """ return self.__notifications_policy - @property def enabled(self): - """ - """ + """ + """ return self.__enabled - + @enabled.setter def enabled(self, value): - """ - """ + """ + """ self.__enabled = value - - + def __repr__(self): """ """ @@ -196,15 +181,15 @@ class WeechatTarget(object): self.__notifications_policy, 'yes' if self.__enabled else 'no') - def send_private_message_notification(self, values): """ """ try: title_str = self.__fetch_formatted_str(self.__pm_title_template, values) - message_str = self.__fetch_formatted_str(self.__pm_message_template, - values) + message_str = self.__fetch_formatted_str( + self.__pm_message_template, + values) post_values = {'title': title_str, 'message': message_str, 'password': self.__password} @@ -220,15 +205,15 @@ class WeechatTarget(object): 'BEINC DEBUG: send_private_message_notification-ERROR ' 'for "{0}": {1}'.format(self.__name, e)) - def send_channel_message_notification(self, values): """ """ try: title_str = self.__fetch_formatted_str(self.__cm_title_template, - values) - message_str = self.__fetch_formatted_str(self.__cm_message_template, - values) + values) + message_str = self.__fetch_formatted_str( + self.__cm_message_template, + values) post_values = {'title': title_str, 'message': message_str, 'password': self.__password} @@ -244,15 +229,15 @@ class WeechatTarget(object): 'BEINC DEBUG: send_channel_message_notification-ERROR ' 'for "{0}": {1}'.format(self.__name, e)) - def send_notify_message_notification(self, values): """ """ try: title_str = self.__fetch_formatted_str(self.__nm_title_template, - values) - message_str = self.__fetch_formatted_str(self.__nm_message_template, - values) + values) + message_str = self.__fetch_formatted_str( + self.__nm_message_template, + values) post_values = {'title': title_str, 'message': message_str, 'password': self.__password} @@ -268,7 +253,6 @@ class WeechatTarget(object): 'BEINC DEBUG: send_notify_message_notification-ERROR ' 'for "{0}": {1}'.format(self.__name, e)) - def __fetch_formatted_str(self, template, values): """ """ @@ -284,16 +268,13 @@ class WeechatTarget(object): template = template.replace(key, value) return template - def __send_beinc_message(self, data): """ the function implements the BEINC "protocol" by generating a simple HTTP request """ - try: req = urllib2.Request(self.__url, data) - if self.__cert_file: opener = urllib2.build_opener(ValidHTTPSHandler) response = opener.open(req) @@ -307,12 +288,14 @@ class WeechatTarget(object): if self.__debug: beinc_prnt( 'BEINC DEBUG: send_beinc_message-ERROR for "{0}": {1} ->' - ' ({2} - {3})'.format(self.__name, e.url, e.code, e.reason)) + ' ({2} - {3})'.format(self.__name, + e.url, + e.code, + e.reason)) # all other exception should be handled by the caller return False - def beinc_prnt(message_str): """ wrapper around weechat.prnt @@ -325,12 +308,11 @@ def beinc_prnt(message_str): def beinc_cmd_target_handler(cmd_tokens): """ - handles: '/beinc target' command actions + handles: '/beinc target' command actions """ if not cmd_tokens or cmd_tokens[0] not in ['list', 'enable', 'disable']: beinc_prnt('beinc target [ list | enable | disable ]') return weechat.WEECHAT_RC_OK - if cmd_tokens[0] == 'list': beinc_prnt('--- Targets ---') for target in target_list: @@ -360,17 +342,14 @@ def beinc_cmd_target_handler(cmd_tokens): break else: beinc_prnt('no matching target for "{0}"'.format(name)) - return weechat.WEECHAT_RC_OK def beinc_command(data, buffer_obj, args): global enabled cmd_tokens = args.split() - if not cmd_tokens: return weechat.WEECHAT_RC_OK - if args == 'on': enabled = True beinc_prnt('BEINC on') @@ -387,17 +366,14 @@ def beinc_command(data, buffer_obj, args): str(data), str(cmd_tokens), str(args))) - return weechat.WEECHAT_RC_OK def beinc_privmsg_handler(data, signal, signal_data): if not enabled: return weechat.WEECHAT_RC_OK - prvmsg_dict = weechat.info_get_hashtable('irc_message_parse', - {'message': signal_data }) - + {'message': signal_data}) # packing the privmsg handler values ph_values = dict() ph_values['server'] = signal.split(',')[0] @@ -406,70 +382,75 @@ def beinc_privmsg_handler(data, signal, signal_data): ph_values['source_nick'] = prvmsg_dict['nick'] ph_values['message'] = ':'.join( prvmsg_dict['arguments'].split(':')[1:]).strip() - if ph_values['channel'] == ph_values['own_nick']: # priv messages are handled here if not global_values['global_private_messages_policy']: return weechat.WEECHAT_RC_OK - - if global_values['global_private_messages_policy'] == BEINC_POLICY_LIST_ONLY \ - and '{0}.{1}'.format( - ph_values['server'], - ph_values['source_nick'].lower()) not in global_values['global_nicks']: + p_messages_policy = global_values['global_private_messages_policy'] + if p_messages_policy == BEINC_POLICY_LIST_ONLY and + '{0}.{1}'.format( + ph_values['server'], + ph_values['source_nick'].lower() + ) not in global_values['global_nicks']: return weechat.WEECHAT_RC_OK - for target in target_list: if not target.enabled: continue - if target.private_messages_policy == BEINC_POLICY_ALL or ( - target.private_messages_policy == BEINC_POLICY_LIST_ONLY \ - and '{0}.{1}'.format( - ph_values['server'], - ph_values['source_nick'].lower()) in target.nicks): + if target.private_messages_policy == BEINC_POLICY_ALL or + ( + target.private_messages_policy == BEINC_POLICY_LIST_ONLY and + '{0}.{1}'.format( + ph_values['server'], + ph_values['source_nick'].lower()) in target.nicks + ): target.send_private_message_notification(ph_values) - - elif ph_values['own_nick'].lower() in ph_values['message'].lower(): + elif ph_values['own_nick'].lower() in ph_values['message'].lower(): # notify messages are handled here if not global_values['global_notifications_policy']: return weechat.WEECHAT_RC_OK - - if global_values['global_notifications_policy'] == BEINC_POLICY_LIST_ONLY \ - and '{0}.{1}'.format( - ph_values['server'], - ph_values['channel'].lower()) not in global_values['global_chans']: + notifications_policy = global_values['global_notifications_policy'] + if notifications_policy == BEINC_POLICY_LIST_ONLY and + ( + '{0}.{1}'.format( + ph_values['server'], + ph_values['channel'].lower() + ) not in global_values['global_chans'] + ): return weechat.WEECHAT_RC_OK - for target in target_list: if not target.enabled: continue if target.notifications_policy == BEINC_POLICY_ALL or ( - target.notifications_policy == BEINC_POLICY_LIST_ONLY \ - and '{0}.{1}'.format( + target.notifications_policy == BEINC_POLICY_LIST_ONLY and + '{0}.{1}'.format( ph_values['server'], - ph_values['channel'].lower()) in target.chans): + ph_values['channel'].lower()) in target.chans + ): target.send_notify_message_notification(ph_values) - - elif global_values['global_channel_messages_policy']: + elif global_values['global_channel_messages_policy']: # chan messages are handled here if not global_values['global_notifications_policy']: return weechat.WEECHAT_RC_OK - - if global_values['global_channel_messages_policy'] == BEINC_POLICY_LIST_ONLY \ - and '{0}.{1}'.format( - ph_values['server'], - ph_values['channel'].lower()) not in global_values['global_chans']: + c_messages_policy = global_values['global_channel_messages_policy'] + if c_messages_policy == BEINC_POLICY_LIST_ONLY and + ( + '{0}.{1}'.format( + ph_values['server'], + ph_values['channel'].lower() + ) not in global_values['global_chans'] + ): return weechat.WEECHAT_RC_OK - for target in target_list: if not target.enabled: continue - if target.channel_messages_policy == BEINC_POLICY_ALL or ( - target.channel_messages_policy == BEINC_POLICY_LIST_ONLY \ - and '{0}.{1}'.format( - ph_values['server'], - ph_values['channel'].lower()) in target.chans): + if target.channel_messages_policy == BEINC_POLICY_ALL or + ( + target.channel_messages_policy == BEINC_POLICY_LIST_ONLY and + '{0}.{1}'.format( + ph_values['server'], + ph_values['channel'].lower()) in target.chans + ): target.send_channel_message_notification(ph_values) - return weechat.WEECHAT_RC_OK @@ -484,7 +465,6 @@ def beinc_init(): global_values['global_chans'] = set() global_values['global_nicks'] = set() target_list = list() - custom_error = '' global_values['global_channel_messages_policy'] = False global_values['global_private_messages_policy'] = False @@ -496,14 +476,13 @@ def beinc_init(): weechat.info_get('weechat_dir', ''), 'beinc.json') beinc_prnt('Parsing {0}...'.format(beinc_config_file_str)) - custom_error = 'load error' with open(beinc_config_file_str, 'r') as fp: config_dict = json.load(fp) - custom_error = 'target parse error' - global_values['use_current_buffer'] = bool(config_dict['irc_client'].get( - 'use_current_buffer', False)) + global_values['use_current_buffer'] = bool( + config_dict['irc_client'].get( + 'use_current_buffer', False)) for target in config_dict['irc_client']['targets']: try: new_target = WeechatTarget(target) @@ -518,32 +497,27 @@ def beinc_init(): global_values['global_private_messages_policy'] = True if new_target.notifications_policy: global_values['global_notifications_policy'] = True - target_list.append(new_target) beinc_prnt('BEINC target "{0}" added'.format(new_target.name)) - beinc_prnt('Done!') - except Exception as e: beinc_prnt('ERROR: unable to parse {0}: {1} - {2}'.format( beinc_config_file_str, custom_error, e)) enabled = False - # do not return error / exit the script # in order to give a smoother opportunity to fix a 'broken' config return weechat.WEECHAT_RC_OK - return weechat.WEECHAT_RC_OK - -weechat.register('beinc_weechat', - 'Simeon Simeonov', - '1.0', - 'GPL3', - 'Blackmore\'s Extended IRC Notification Collection (Weechat Client)', - '', - '') +weechat.register( + 'beinc_weechat', + 'Simeon Simeonov', + '1.0', + 'GPL3', + 'Blackmore\'s Extended IRC Notification Collection (Weechat Client)', + '', + '') version = weechat.info_get('version_number', '') or 0 if int(version) < 0x00040000: weechat.prnt('', 'WeeChat version >= 0.4.0 is required to run beinc') -- cgit v1.3