From 504c118c5535d3e2e1c943e9ae354b1048604be3 Mon Sep 17 00:00:00 2001 From: Simeon Simeonov Date: Fri, 20 Dec 2013 21:42:03 +0100 Subject: Several modifications --- beinc_server.json | 20 +++++++- beinc_server.py | 52 ++++++-------------- beinc_weechat.py | 144 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ weechat_notify.py | 3 +- 4 files changed, 180 insertions(+), 39 deletions(-) create mode 100644 beinc_weechat.py diff --git a/beinc_server.json b/beinc_server.json index 8fa042c..0bdcc8a 100644 --- a/beinc_server.json +++ b/beinc_server.json @@ -17,7 +17,25 @@ ] }, - "client": {}, + "irc_client": { + "targets": [ + { + "name": "weechat_main", + "target_url": "", + "target_password": "changeme", + "title_template": "", + "message_template": "", + "channel_list": ["RedpillLinpro.#python", + "Exile.#hin", + "RedpillLinpro.#adult", + "Exile.#pichove"], + "nick_list": "", + "channel_messages_policy": 0, + "private_messages_policy": 0, + "notifications_policy": 0 + } + ] + }, "config_version": 1 diff --git a/beinc_server.py b/beinc_server.py index da47e22..300c954 100755 --- a/beinc_server.py +++ b/beinc_server.py @@ -19,12 +19,11 @@ BEINC_OSD_TYPE_NONE = 0 BEINC_OSD_TYPE_PYNOTIFY = 1 - class BEINCInstance(object): """ Represents a single server-instance """ - + def __init__(self, instance_dict): """ instance_dict: the config-dictionary node that represents this instance @@ -38,7 +37,7 @@ class BEINCInstance(object): self.__name = instance_dict['name'] self.__password = instance_dict['password'] self.__queue_size = int(instance_dict['queue_size']) - + except Exception as e: sys.stderr.write( 'Instance processing error {0}:\n{1}\n'.format(self.__name, @@ -50,7 +49,8 @@ class BEINCInstance(object): sys.stderr.write( 'This server does not possess pynotify capability\n') sys.stderr.write( - "Remove the instance {0} or define it with 'osd_system': 'none'") + 'Remove the instance {0}'.format(self.__name)) + sys.stderr.write("or define it with 'osd_system': 'none'\n") sys.exit(1) try: @@ -58,7 +58,7 @@ class BEINCInstance(object): self.__osd_notification.set_timeout( instance_dict['osd_timeout']) self.__osd_notification.set_property( - 'app_name', + 'app_name', '{0} {1}'.format(sys.argv[0], __version__)) except Exception as e: sys.stderr.write( @@ -67,7 +67,6 @@ class BEINCInstance(object): self.__osd_type = BEINC_OSD_TYPE_PYNOTIFY - @property def name(self): """ @@ -75,7 +74,6 @@ class BEINCInstance(object): """ return self.__name - @property def queueable(self): """ @@ -83,18 +81,13 @@ class BEINCInstance(object): """ return bool(self.__queue_size) - def password_match(self, password): """ Returns True if 'passowrd' matches the instance-password, otherwise - False """ - if self.__password == password: - return True + return True if self.__password == password else False - return False - - def send_message(self, title, message): """ Displays or enqueues the message, @@ -105,7 +98,6 @@ class BEINCInstance(object): else: self.__send_message_to_queue(title, message) - def get_queue(self): """ Reruens a json representation of the message queue @@ -114,7 +106,6 @@ class BEINCInstance(object): self.__message_queue = list() return jstr - def __send_pynotify_messaage(self, title, message): """ Displays pynotify message @@ -123,7 +114,6 @@ class BEINCInstance(object): self.__osd_notification.set_properties(summary=title, body=message) self.__osd_notification.show() - def __send_message_to_queue(self, title, message): """ Enqueues the message @@ -135,7 +125,6 @@ class BEINCInstance(object): self.__message_queue.append({'title': title, 'message': message}) - def beinc_instance_login(method): """ decorator for checking login credentials @@ -160,20 +149,16 @@ def beinc_instance_login(method): sys.stderr.write('Wrong instance or password: {0}\n'.format(e)) raise cherrypy.HTTPError('403 Forbidden', 'Wrong instance or password') - - print('First') if not instance.password_match(kwargs.get('password')): - raise cherrypy.HTTPError('403 Forbidden', + raise cherrypy.HTTPError('403 Forbidden', 'Wrong instance or password') - print('second') return method(self, *args, **kwargs) return tmp_func - class WebNotifyServer(object): def __init__(self, config): @@ -191,7 +176,6 @@ class WebNotifyServer(object): sys.stderr.write('Unable to initialize queues: {0}\n'.format(e)) sys.exit(1) - @cherrypy.expose def index(self): """ @@ -199,7 +183,6 @@ class WebNotifyServer(object): """ return 'index' - @cherrypy.expose def default(self, *args): """ @@ -207,7 +190,6 @@ class WebNotifyServer(object): """ return 'default' - @cherrypy.expose def push(self, *args, **kwargs): print('push called') @@ -227,10 +209,10 @@ class WebNotifyServer(object): sys.stderr.write('Wrong instance or password: {0}\n'.format(e)) raise cherrypy.HTTPError('403 Forbidden', 'Wrong instance or password') - + if not instance.password_match(kwargs.get('password')): sys.stderr.write('Wrong instance or password: {0}\n'.format(e)) - raise cherrypy.HTTPError('403 Forbidden', + raise cherrypy.HTTPError('403 Forbidden', 'Wrong instance or password') # instance = self.__instances[args[0]] @@ -242,11 +224,10 @@ class WebNotifyServer(object): except Exception as e: sys.stderr.write( 'Unable to handle message in {0}: ({1})\n'.format( - instance.name, + instance.name, e)) raise cherrypy.HTTPError(500, 'Unable to send message') - @cherrypy.expose @beinc_instance_login def pull(self, *args, **kwargs): @@ -255,12 +236,11 @@ class WebNotifyServer(object): return 'OK' - def main(): - parser = argparse.ArgumentParser(description='The following options are available') + parser = argparse.ArgumentParser( + description='The following options are available') - parser.add_argument('-d', action='store_true', dest='daemonize', @@ -295,14 +275,13 @@ def main(): 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.stderr.write('Unable to parse {0}: {1}'.format(args.config_file, + e)) cherrypy.config.update({ 'server.socket_host': args.hostname, @@ -317,7 +296,7 @@ def main(): global pynotify try: import pynotify - if not pynotify.init("BEINC Notify"): + if not pynotify.init('BEINC Notify'): sys.stderr.write('pynotify.init failed! Exiting...\n') sys.exit(1) except Exception as e: @@ -337,4 +316,3 @@ def main(): if __name__ == "__main__": main() - diff --git a/beinc_weechat.py b/beinc_weechat.py new file mode 100644 index 0000000..4abf6f1 --- /dev/null +++ b/beinc_weechat.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import json +import os +import socket +import sys + +import weechat + +enabled = True + +class WeechatTarget(object): + """ + """ + + def __init__(self, target_dict): + """ + target_dict: the config-dictionary node that represents this instance + """ + + self.__name = target_dict['name'] + self.__url = target_dict['target_url'] + self.__password = target_dict['target_password'] + self.__title_template = target_dict['title_template'] + self.__message_template = target_dict['message_template'] + self.__failed = False + + + + +def bosd_send_xosd_message(message): + for conn in connections: + try: + #weechat.prnt("", message) + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect((conn['sbosdd_ip'], conn['sbosdd_port'])) + s.send(message) + s.close() + except: + continue + + return True + + +def bosd_command(data, buffer, args): + global enabled + if args == 'on': + enabled = True + weechat.prnt(weechat.current_buffer(), 'bosd on') + elif args == 'off': + enabled = False + weechat.prnt(weechat.current_buffer(), 'bosd off') + elif args == 'reload': + weechat.prnt(weechat.current_buffer(), '{0} reloaded') + else: + bosd_send_xosd_message(args) + + return weechat.WEECHAT_RC_OK + + +def bosd_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 }) + + + server = signal.split(",")[0] + + # channel = signal_data.split(":")[-1] + # my_nick = weechat.info_get("irc_nick_from_host", signal_data) + + my_nick = weechat.info_get("irc_nick", server) + channel = prvmsg_dict['arguments'].split(":")[0].strip() + nick = prvmsg_dict['nick'] + message = ':'.join(prvmsg_dict['arguments'].split(':')[1:]).strip() + + if (my_nick.lower() in message.lower()) or ('{0}.{1}'.format(server,channel.lower()) in notify_channels): + template_msg = '{0} @ {1} - {2}: {3}'.format(channel, + server, + nick, + message) + bosd_send_xosd_message(template_msg) + + if my_nick.lower() in channel.lower(): + template_msg = '{0} @ {1}: {2}'.format(nick, server, message) + bosd_send_xosd_message(template_msg) + + # weechat.prnt("", + # 'DEBUG: my_nick - {0}, server - {1}, channel - {2}'.format(my_nick, + # server, + # channel)) + + return weechat.WEECHAT_RC_OK + + +def beinc_init(): + + global enabled + global target_list + + custom_error = '' + + try: + beinc_config_file_str = os.path.join(weechat.info_get('weechat_dir', + ''), + 'beinc.json') + weechat.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) + + # clear the target-list + target_list = [] + + custom_error = 'target parse error' + for target in config_dict['irc_client']['targets']: + new_target = WeechatTarget(target) + target_list.append(new_target) + + weechat.prnt('', 'Done!!!') + + except Exception as e: + weechat.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.hook_command('beinc', 'beinc on off toggle', '', 'description...', 'None', 'beinc_command', '') +weechat.hook_signal('*,irc_in2_privmsg', 'beinc_privmsg_handler', '') + +beinc_init() + +weechat.prnt('', 'beinc initiated!') diff --git a/weechat_notify.py b/weechat_notify.py index f070551..897f26d 100755 --- a/weechat_notify.py +++ b/weechat_notify.py @@ -13,6 +13,7 @@ POLLING_FREQUENCY = 10 NOTIFICATION_URL = 'https://simeon.simeonov.no:40004/notifications/' TIMEOUT_SEC = 3 + def poll_notifications(scheduler): """ """ @@ -20,7 +21,7 @@ def poll_notifications(scheduler): req = urllib2.Request(NOTIFICATION_URL) response = urllib2.urlopen(req) response_str = response.read() - + entries = json.loads(response_str) for entry in entries: n = pynotify.Notification('IRC', entry, 'dialog-information') -- cgit v1.3