summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSimeon Simeonov2014-05-08 10:25:39 +0200
committerSimeon Simeonov2014-05-08 10:25:39 +0200
commite4e15e7f4e594efc899016ba17cabd02fa344600 (patch)
treea90786c2a56c288c0e0f541f6b9a1f0c81dedec5
parent60f47b04174d016cc86c6e06fdaf0794c3d14216 (diff)
Forcing PEP8 compatibility
-rwxr-xr-xbeinc_generic_client.py15
-rwxr-xr-xbeinc_server.py53
-rw-r--r--beinc_weechat.py202
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):
55 cert_reqs=ssl.CERT_REQUIRED) 55 cert_reqs=ssl.CERT_REQUIRED)
56 56
57 57
58
59class ValidHTTPSHandler(urllib2.HTTPSHandler): 58class ValidHTTPSHandler(urllib2.HTTPSHandler):
60 """ 59 """
61 Implements a simple CERT verification functionality 60 Implements a simple CERT verification functionality
@@ -65,7 +64,6 @@ class ValidHTTPSHandler(urllib2.HTTPSHandler):
65 return self.do_open(ValidHTTPSConnection, req) 64 return self.do_open(ValidHTTPSConnection, req)
66 65
67 66
68
69def action_push(args): 67def action_push(args):
70 """ 68 """
71 """ 69 """
@@ -90,66 +88,57 @@ def action_push(args):
90 print('Body:\n{0}'.format(response.read())) 88 print('Body:\n{0}'.format(response.read()))
91 response.close() 89 response.close()
92 except urllib2.HTTPError as e: 90 except urllib2.HTTPError as e:
93 sys.stderr.write('BEINC-server error ({0} - {1})\n'.format(e.code, e.reason)) 91 sys.stderr.write('BEINC-server error ({0} - {1})\n'.format(e.code,
92 e.reason))
94 except Exception as e: 93 except Exception as e:
95 sys.stderr.write('BEINC generic client error: {0}\n'.format(e)) 94 sys.stderr.write('BEINC generic client error: {0}\n'.format(e))
96 sys.exit(errno.EPERM) 95 sys.exit(errno.EPERM)
97 96
98 97
99def main(): 98def main():
100
101 parser = argparse.ArgumentParser( 99 parser = argparse.ArgumentParser(
102 description='The following options are available') 100 description='The following options are available')
103
104 parser.add_argument('url', 101 parser.add_argument('url',
105 metavar='URL', 102 metavar='URL',
106 type=str, 103 type=str,
107 #dest='url', 104 #dest='url',
108 #required=True, 105 #required=True,
109 help='Destination URL') 106 help='Destination URL')
110
111 parser.add_argument('-c', '--cert-file', 107 parser.add_argument('-c', '--cert-file',
112 metavar='FILE', 108 metavar='FILE',
113 type=str, 109 type=str,
114 dest='cert', 110 dest='cert',
115 default='', 111 default='',
116 help='BEINC CA-cert to check the server-cert against') 112 help='BEINC CA-cert to check the server-cert against')
117
118 parser.add_argument('-m', '--message', 113 parser.add_argument('-m', '--message',
119 metavar='MESSAGE', 114 metavar='MESSAGE',
120 type=str, 115 type=str,
121 dest='message', 116 dest='message',
122 default='BEINC message', 117 default='BEINC message',
123 help='BEINC message') 118 help='BEINC message')
124
125 parser.add_argument('-p', '--password', 119 parser.add_argument('-p', '--password',
126 metavar='PASSWORD', 120 metavar='PASSWORD',
127 type=str, 121 type=str,
128 dest='password', 122 dest='password',
129 default='', 123 default='',
130 help='Password') 124 help='Password')
131
132 parser.add_argument('-t', '--title', 125 parser.add_argument('-t', '--title',
133 metavar='TITLE', 126 metavar='TITLE',
134 type=str, 127 type=str,
135 dest='title', 128 dest='title',
136 default='BEINC title', 129 default='BEINC title',
137 help='BEINC title') 130 help='BEINC title')
138
139 parser.add_argument('-v', '--version', 131 parser.add_argument('-v', '--version',
140 action='version', 132 action='version',
141 version='%(prog)s {0}'.format(__version__), 133 version='%(prog)s {0}'.format(__version__),
142 help='display program-version and exit') 134 help='display program-version and exit')
143
144 args = parser.parse_args() 135 args = parser.parse_args()
145
146 if not args.password: 136 if not args.password:
147 try: 137 try:
148 args.password = getpass.getpass() 138 args.password = getpass.getpass()
149 except Exception as e: 139 except Exception as e:
150 sys.stderr.write('Prompt terminated\n') 140 sys.stderr.write('Prompt terminated\n')
151 sys.exit(errno.EACCES) 141 sys.exit(errno.EACCES)
152
153 action_push(args) 142 action_push(args)
154 sys.exit(0) 143 sys.exit(0)
155 144
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):
52 """ 52 """
53 instance_dict: the config-dictionary node that represents this instance 53 instance_dict: the config-dictionary node that represents this instance
54 """ 54 """
55
56 self.__message_queue = list() 55 self.__message_queue = list()
57 self.__osd_type = BEINC_OSD_TYPE_NONE 56 self.__osd_type = BEINC_OSD_TYPE_NONE
58 self.__osd_notification = None 57 self.__osd_notification = None
@@ -60,7 +59,6 @@ class BEINCInstance(object):
60 self.__name = instance_dict.get('name') 59 self.__name = instance_dict.get('name')
61 self.__password = instance_dict.get('password', '') 60 self.__password = instance_dict.get('password', '')
62 self.__queue_size = int(instance_dict.get('queue_size', 3)) 61 self.__queue_size = int(instance_dict.get('queue_size', 3))
63
64 if instance_dict['osd_system'].lower() == 'pynotify': 62 if instance_dict['osd_system'].lower() == 'pynotify':
65 self.__queue_size = 0 # disable queueing 63 self.__queue_size = 0 # disable queueing
66 if not pynotify: 64 if not pynotify:
@@ -70,7 +68,6 @@ class BEINCInstance(object):
70 'Remove the instance {0}'.format(self.__name)) 68 'Remove the instance {0}'.format(self.__name))
71 sys.stderr.write("or define it with 'osd_system': 'none'\n") 69 sys.stderr.write("or define it with 'osd_system': 'none'\n")
72 sys.exit(errno.EPERM) 70 sys.exit(errno.EPERM)
73
74 try: 71 try:
75 self.__osd_notification = pynotify.Notification(' ') 72 self.__osd_notification = pynotify.Notification(' ')
76 self.__osd_notification.set_timeout( 73 self.__osd_notification.set_timeout(
@@ -82,10 +79,8 @@ class BEINCInstance(object):
82 sys.stderr.write( 79 sys.stderr.write(
83 'Unable to set up a notification object for {0} ({1})\n') 80 'Unable to set up a notification object for {0} ({1})\n')
84 sys.exit(errno.EPERM) 81 sys.exit(errno.EPERM)
85
86 self.__osd_type = BEINC_OSD_TYPE_PYNOTIFY 82 self.__osd_type = BEINC_OSD_TYPE_PYNOTIFY
87 83
88
89 @property 84 @property
90 def name(self): 85 def name(self):
91 """ 86 """
@@ -129,7 +124,6 @@ class BEINCInstance(object):
129 """ 124 """
130 Displays pynotify message 125 Displays pynotify message
131 """ 126 """
132
133 self.__osd_notification.set_properties(summary=title, body=message) 127 self.__osd_notification.set_properties(summary=title, body=message)
134 self.__osd_notification.show() 128 self.__osd_notification.show()
135 129
@@ -137,10 +131,8 @@ class BEINCInstance(object):
137 """ 131 """
138 Enqueues the message 132 Enqueues the message
139 """ 133 """
140
141 if len(self.__message_queue) >= self.__queue_size: 134 if len(self.__message_queue) >= self.__queue_size:
142 self.__message_queue.pop(0) 135 self.__message_queue.pop(0)
143
144 self.__message_queue.append({'title': title, 'message': message}) 136 self.__message_queue.append({'title': title, 'message': message})
145 137
146 138
@@ -150,20 +142,16 @@ def beinc_instance_login(method):
150 """ 142 """
151 143
152 def wrapper(self, *args, **kwargs): 144 def wrapper(self, *args, **kwargs):
153
154 if not args: 145 if not args:
155 raise cherrypy.HTTPError(status = 404) 146 raise cherrypy.HTTPError(status=404)
156
157 try: 147 try:
158 instance = self.instances[args[0]] 148 instance = self.instances[args[0]]
159 except Exception as e: 149 except Exception as e:
160 raise cherrypy.HTTPError(status = 401, 150 raise cherrypy.HTTPError(status=401,
161 message = 'Wrong instance or password') 151 message='Wrong instance or password')
162
163 if not instance.password_match(kwargs.get('password')): 152 if not instance.password_match(kwargs.get('password')):
164 raise cherrypy.HTTPError(status = 401, 153 raise cherrypy.HTTPError(status=401,
165 message = 'Wrong instance or password') 154 message='Wrong instance or password')
166
167 return method(self, *args, **kwargs) 155 return method(self, *args, **kwargs)
168 156
169 return wrapper 157 return wrapper
@@ -176,7 +164,6 @@ class WebNotifyServer(object):
176 """ 164 """
177 self.__config = config 165 self.__config = config
178 self.__instances = dict() 166 self.__instances = dict()
179
180 # initialize pynotify if the module exists and if needed 167 # initialize pynotify if the module exists and if needed
181 if pynotify: 168 if pynotify:
182 for instance in self.__config['server']['instances']: 169 for instance in self.__config['server']['instances']:
@@ -191,14 +178,12 @@ class WebNotifyServer(object):
191 for instance in self.__config['server']['instances']: 178 for instance in self.__config['server']['instances']:
192 self.__instances[instance['name']] = BEINCInstance(instance) 179 self.__instances[instance['name']] = BEINCInstance(instance)
193 print('Instance "{0}" added'.format(instance['name'])) 180 print('Instance "{0}" added'.format(instance['name']))
194
195 except Exception as e: 181 except Exception as e:
196 sys.stderr.write('Unable to create instance "{0}": {1}\n'.format( 182 sys.stderr.write('Unable to create instance "{0}": {1}\n'.format(
197 instance['name'], 183 instance['name'],
198 e)) 184 e))
199 sys.exit(1) 185 sys.exit(1)
200 186
201
202 @property 187 @property
203 def instances(self): 188 def instances(self):
204 return self.__instances 189 return self.__instances
@@ -217,14 +202,11 @@ class WebNotifyServer(object):
217 """ 202 """
218 return 'default' 203 return 'default'
219 204
220
221 @cherrypy.expose 205 @cherrypy.expose
222 @beinc_instance_login 206 @beinc_instance_login
223 def push(self, *args, **kwargs): 207 def push(self, *args, **kwargs):
224
225 instance = self.__instances[args[0]] 208 instance = self.__instances[args[0]]
226 209 ##print('**kwargs: {0}'.format(str(kwargs)))
227 print('**kwargs: {0}'.format(str(kwargs)))
228 title = kwargs.get('title', '') 210 title = kwargs.get('title', '')
229 message = kwargs.get('message', '') 211 message = kwargs.get('message', '')
230 try: 212 try:
@@ -237,18 +219,15 @@ class WebNotifyServer(object):
237 e)) 219 e))
238 raise cherrypy.HTTPError(500, 'Unable to send message') 220 raise cherrypy.HTTPError(500, 'Unable to send message')
239 221
240
241 @cherrypy.expose 222 @cherrypy.expose
242 @beinc_instance_login 223 @beinc_instance_login
243 def pull(self, *args, **kwargs): 224 def pull(self, *args, **kwargs):
244
245 instance = self.__instances[args[0]] 225 instance = self.__instances[args[0]]
246 if not instance.queueable: 226 if not instance.queueable:
247 raise cherrypy.HTTPError( 227 raise cherrypy.HTTPError(
248 status = 405, 228 status=405,
249 message = 'BEINC instance "{0}" does not support queuing'.format( 229 message='BEINC instance "{0}" does not support queuing'.format(
250 instance.name)) 230 instance.name))
251
252 return instance.get_queue() 231 return instance.get_queue()
253 232
254 233
@@ -256,56 +235,51 @@ def main():
256 235
257 parser = argparse.ArgumentParser( 236 parser = argparse.ArgumentParser(
258 description='The following options are available') 237 description='The following options are available')
259
260 parser.add_argument('-d', 238 parser.add_argument('-d',
261 action='store_true', 239 action='store_true',
262 dest='daemonize', 240 dest='daemonize',
263 default=False, 241 default=False,
264 help='daemonize the server process') 242 help='daemonize the server process')
265
266 parser.add_argument('-H', '--hostname', 243 parser.add_argument('-H', '--hostname',
267 metavar='HOSTNAME', 244 metavar='HOSTNAME',
268 type=str, 245 type=str,
269 dest='hostname', 246 dest='hostname',
270 default='127.0.0.1', 247 default='127.0.0.1',
271 help="Server IP / hostname") 248 help="Server IP / hostname")
272
273 parser.add_argument('-p', '--port', 249 parser.add_argument('-p', '--port',
274 metavar='PORT', 250 metavar='PORT',
275 type=int, 251 type=int,
276 dest='port', 252 dest='port',
277 default=9998, 253 default=9998,
278 help="Server port") 254 help="Server port")
279
280 parser.add_argument('-c', '--config-file', 255 parser.add_argument('-c', '--config-file',
281 metavar='FILE', 256 metavar='FILE',
282 type=str, 257 type=str,
283 default=os.path.expanduser('~/.beinc_server.json'), 258 default=os.path.expanduser('~/.beinc_server.json'),
284 dest='config_file', 259 dest='config_file',
285 help="config file") 260 help="config file")
286
287 parser.add_argument('-v', '--version', 261 parser.add_argument('-v', '--version',
288 action='version', 262 action='version',
289 version='%(prog)s {0}'.format(__version__), 263 version='%(prog)s {0}'.format(__version__),
290 help='display program-version and exit') 264 help='display program-version and exit')
291
292 args = parser.parse_args() 265 args = parser.parse_args()
293 266
294 try: 267 try:
295 with open(args.config_file, 'r') as fp: 268 with open(args.config_file, 'r') as fp:
296 config_dict = json.load(fp) 269 config_dict = json.load(fp)
297
298 except Exception as e: 270 except Exception as e:
299 sys.stderr.write('Unable to parse {0}: {1}'.format(args.config_file, 271 sys.stderr.write('Unable to parse {0}: {1}'.format(args.config_file,
300 e)) 272 e))
301 sys.exit(errno.EIO) 273 sys.exit(errno.EIO)
302 274
275 ssl_certificate = config_dict['server']['general']['ssl_certificate']
276 ssl_private_key = config_dict['server']['general']['ssl_private_key']
303 cherrypy.config.update({ 277 cherrypy.config.update({
304 'server.socket_host': args.hostname, 278 'server.socket_host': args.hostname,
305 'server.socket_port': args.port, 279 'server.socket_port': args.port,
306 'server.ssl_module': config_dict['server']['general']['ssl_module'].encode('utf-8'), 280 'server.ssl_module': config_dict['server']['general']['ssl_module'],
307 'server.ssl_certificate': config_dict['server']['general']['ssl_certificate'], 281 'server.ssl_certificate': ssl_certificate,
308 'server.ssl_private_key': config_dict['server']['general']['ssl_private_key'], 282 'server.ssl_private_key': ssl_private_key,
309 'tools.encode.on': True, 283 'tools.encode.on': True,
310 'tools.encode.encoding': 'utf-8', 284 'tools.encode.encoding': 'utf-8',
311 'tools.log_tracebacks.on': False, 285 'tools.log_tracebacks.on': False,
@@ -314,7 +288,6 @@ def main():
314 288
315 try: 289 try:
316 cherrypy.quickstart(WebNotifyServer(config_dict)) 290 cherrypy.quickstart(WebNotifyServer(config_dict))
317
318 except Exception as e: 291 except Exception as e:
319 sys.stderr.write("WebServer error: {0}".format(e)) 292 sys.stderr.write("WebServer error: {0}".format(e))
320 sys.exit(1) 293 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
46BEINC_POLICY_LIST_ONLY = 2 46BEINC_POLICY_LIST_ONLY = 2
47 47
48 48
49
50class ValidHTTPSConnection(httplib.HTTPConnection): 49class ValidHTTPSConnection(httplib.HTTPConnection):
51 """ 50 """
52 Implements a simple CERT verification functionality 51 Implements a simple CERT verification functionality
@@ -68,7 +67,6 @@ class ValidHTTPSConnection(httplib.HTTPConnection):
68 cert_reqs=ssl.CERT_REQUIRED) 67 cert_reqs=ssl.CERT_REQUIRED)
69 68
70 69
71
72class ValidHTTPSHandler(urllib2.HTTPSHandler): 70class ValidHTTPSHandler(urllib2.HTTPSHandler):
73 """ 71 """
74 Implements a simple CERT verification functionality 72 Implements a simple CERT verification functionality
@@ -78,11 +76,10 @@ class ValidHTTPSHandler(urllib2.HTTPSHandler):
78 return self.do_open(ValidHTTPSConnection, req) 76 return self.do_open(ValidHTTPSConnection, req)
79 77
80 78
81
82class WeechatTarget(object): 79class WeechatTarget(object):
83 """ 80 """
84 """ 81 """
85 82
86 def __init__(self, target_dict): 83 def __init__(self, target_dict):
87 """ 84 """
88 target_dict: the config-dictionary node that represents this instance 85 target_dict: the config-dictionary node that represents this instance
@@ -92,22 +89,18 @@ class WeechatTarget(object):
92 ''.join([chr(random.randrange(97, 123)) for x in range(4)])) 89 ''.join([chr(random.randrange(97, 123)) for x in range(4)]))
93 self.__url = target_dict.get('target_url') 90 self.__url = target_dict.get('target_url')
94 self.__password = target_dict.get('target_password') 91 self.__password = target_dict.get('target_password')
95
96 self.__pm_title_template = target_dict.get('pm_title_template', 92 self.__pm_title_template = target_dict.get('pm_title_template',
97 '%s @ %S') 93 '%s @ %S')
98 self.__pm_message_template = target_dict.get('pm_message_template', 94 self.__pm_message_template = target_dict.get('pm_message_template',
99 '%m') 95 '%m')
100
101 self.__cm_title_template = target_dict.get('cm_title_template', 96 self.__cm_title_template = target_dict.get('cm_title_template',
102 '%c @ %S') 97 '%c @ %S')
103 self.__cm_message_template = target_dict.get('cm_message_template', 98 self.__cm_message_template = target_dict.get('cm_message_template',
104 '%s -> %m') 99 '%s -> %m')
105
106 self.__nm_title_template = target_dict.get('nm_title_template', 100 self.__nm_title_template = target_dict.get('nm_title_template',
107 '%c @ %S') 101 '%c @ %S')
108 self.__nm_message_template = target_dict.get('nm_message_template', 102 self.__nm_message_template = target_dict.get('nm_message_template',
109 '%s -> %m') 103 '%s -> %m')
110
111 self.__chans = set(target_dict.get('channel_list', list())) 104 self.__chans = set(target_dict.get('channel_list', list()))
112 self.__nicks = set(target_dict.get('nick_list', list())) 105 self.__nicks = set(target_dict.get('nick_list', list()))
113 self.__chan_messages_policy = int(target_dict.get( 106 self.__chan_messages_policy = int(target_dict.get(
@@ -125,62 +118,54 @@ class WeechatTarget(object):
125 self.__debug = bool(target_dict.get('debug', False)) 118 self.__debug = bool(target_dict.get('debug', False))
126 self.__enabled = bool(target_dict.get('enabled', True)) 119 self.__enabled = bool(target_dict.get('enabled', True))
127 120
128
129 @property 121 @property
130 def name(self): 122 def name(self):
131 """ 123 """
132 """ 124 """
133 return self.__name 125 return self.__name
134 126
135
136 @property 127 @property
137 def chans(self): 128 def chans(self):
138 """ 129 """
139 """ 130 """
140 return self.__chans 131 return self.__chans
141 132
142
143 @property 133 @property
144 def nicks(self): 134 def nicks(self):
145 """ 135 """
146 """ 136 """
147 return self.__nicks 137 return self.__nicks
148
149 138
150 @property 139 @property
151 def channel_messages_policy(self): 140 def channel_messages_policy(self):
152 """ 141 """
153 """ 142 """
154 return self.__chan_messages_policy 143 return self.__chan_messages_policy
155 144
156
157 @property 145 @property
158 def private_messages_policy(self): 146 def private_messages_policy(self):
159 """ 147 """
160 """ 148 """
161 return self.__priv_messages_policy 149 return self.__priv_messages_policy
162 150
163
164 @property 151 @property
165 def notifications_policy(self): 152 def notifications_policy(self):
166 """ 153 """
167 """ 154 """
168 return self.__notifications_policy 155 return self.__notifications_policy
169
170 156
171 @property 157 @property
172 def enabled(self): 158 def enabled(self):
173 """ 159 """
174 """ 160 """
175 return self.__enabled 161 return self.__enabled
176 162
177 @enabled.setter 163 @enabled.setter
178 def enabled(self, value): 164 def enabled(self, value):
179 """ 165 """
180 """ 166 """
181 self.__enabled = value 167 self.__enabled = value
182 168
183
184 def __repr__(self): 169 def __repr__(self):
185 """ 170 """
186 """ 171 """
@@ -196,15 +181,15 @@ class WeechatTarget(object):
196 self.__notifications_policy, 181 self.__notifications_policy,
197 'yes' if self.__enabled else 'no') 182 'yes' if self.__enabled else 'no')
198 183
199
200 def send_private_message_notification(self, values): 184 def send_private_message_notification(self, values):
201 """ 185 """
202 """ 186 """
203 try: 187 try:
204 title_str = self.__fetch_formatted_str(self.__pm_title_template, 188 title_str = self.__fetch_formatted_str(self.__pm_title_template,
205 values) 189 values)
206 message_str = self.__fetch_formatted_str(self.__pm_message_template, 190 message_str = self.__fetch_formatted_str(
207 values) 191 self.__pm_message_template,
192 values)
208 post_values = {'title': title_str, 193 post_values = {'title': title_str,
209 'message': message_str, 194 'message': message_str,
210 'password': self.__password} 195 'password': self.__password}
@@ -220,15 +205,15 @@ class WeechatTarget(object):
220 'BEINC DEBUG: send_private_message_notification-ERROR ' 205 'BEINC DEBUG: send_private_message_notification-ERROR '
221 'for "{0}": {1}'.format(self.__name, e)) 206 'for "{0}": {1}'.format(self.__name, e))
222 207
223
224 def send_channel_message_notification(self, values): 208 def send_channel_message_notification(self, values):
225 """ 209 """
226 """ 210 """
227 try: 211 try:
228 title_str = self.__fetch_formatted_str(self.__cm_title_template, 212 title_str = self.__fetch_formatted_str(self.__cm_title_template,
229 values) 213 values)
230 message_str = self.__fetch_formatted_str(self.__cm_message_template, 214 message_str = self.__fetch_formatted_str(
231 values) 215 self.__cm_message_template,
216 values)
232 post_values = {'title': title_str, 217 post_values = {'title': title_str,
233 'message': message_str, 218 'message': message_str,
234 'password': self.__password} 219 'password': self.__password}
@@ -244,15 +229,15 @@ class WeechatTarget(object):
244 'BEINC DEBUG: send_channel_message_notification-ERROR ' 229 'BEINC DEBUG: send_channel_message_notification-ERROR '
245 'for "{0}": {1}'.format(self.__name, e)) 230 'for "{0}": {1}'.format(self.__name, e))
246 231
247
248 def send_notify_message_notification(self, values): 232 def send_notify_message_notification(self, values):
249 """ 233 """
250 """ 234 """
251 try: 235 try:
252 title_str = self.__fetch_formatted_str(self.__nm_title_template, 236 title_str = self.__fetch_formatted_str(self.__nm_title_template,
253 values) 237 values)
254 message_str = self.__fetch_formatted_str(self.__nm_message_template, 238 message_str = self.__fetch_formatted_str(
255 values) 239 self.__nm_message_template,
240 values)
256 post_values = {'title': title_str, 241 post_values = {'title': title_str,
257 'message': message_str, 242 'message': message_str,
258 'password': self.__password} 243 'password': self.__password}
@@ -268,7 +253,6 @@ class WeechatTarget(object):
268 'BEINC DEBUG: send_notify_message_notification-ERROR ' 253 'BEINC DEBUG: send_notify_message_notification-ERROR '
269 'for "{0}": {1}'.format(self.__name, e)) 254 'for "{0}": {1}'.format(self.__name, e))
270 255
271
272 def __fetch_formatted_str(self, template, values): 256 def __fetch_formatted_str(self, template, values):
273 """ 257 """
274 """ 258 """
@@ -284,16 +268,13 @@ class WeechatTarget(object):
284 template = template.replace(key, value) 268 template = template.replace(key, value)
285 return template 269 return template
286 270
287
288 def __send_beinc_message(self, data): 271 def __send_beinc_message(self, data):
289 """ 272 """
290 the function implements the BEINC "protocol" by generating a simple 273 the function implements the BEINC "protocol" by generating a simple
291 HTTP request 274 HTTP request
292 """ 275 """
293
294 try: 276 try:
295 req = urllib2.Request(self.__url, data) 277 req = urllib2.Request(self.__url, data)
296
297 if self.__cert_file: 278 if self.__cert_file:
298 opener = urllib2.build_opener(ValidHTTPSHandler) 279 opener = urllib2.build_opener(ValidHTTPSHandler)
299 response = opener.open(req) 280 response = opener.open(req)
@@ -307,12 +288,14 @@ class WeechatTarget(object):
307 if self.__debug: 288 if self.__debug:
308 beinc_prnt( 289 beinc_prnt(
309 'BEINC DEBUG: send_beinc_message-ERROR for "{0}": {1} ->' 290 'BEINC DEBUG: send_beinc_message-ERROR for "{0}": {1} ->'
310 ' ({2} - {3})'.format(self.__name, e.url, e.code, e.reason)) 291 ' ({2} - {3})'.format(self.__name,
292 e.url,
293 e.code,
294 e.reason))
311 # all other exception should be handled by the caller 295 # all other exception should be handled by the caller
312 return False 296 return False
313 297
314 298
315
316def beinc_prnt(message_str): 299def beinc_prnt(message_str):
317 """ 300 """
318 wrapper around weechat.prnt 301 wrapper around weechat.prnt
@@ -325,12 +308,11 @@ def beinc_prnt(message_str):
325 308
326def beinc_cmd_target_handler(cmd_tokens): 309def beinc_cmd_target_handler(cmd_tokens):
327 """ 310 """
328 handles: '/beinc target' command actions 311 handles: '/beinc target' command actions
329 """ 312 """
330 if not cmd_tokens or cmd_tokens[0] not in ['list', 'enable', 'disable']: 313 if not cmd_tokens or cmd_tokens[0] not in ['list', 'enable', 'disable']:
331 beinc_prnt('beinc target [ list | enable <name> | disable <name> ]') 314 beinc_prnt('beinc target [ list | enable <name> | disable <name> ]')
332 return weechat.WEECHAT_RC_OK 315 return weechat.WEECHAT_RC_OK
333
334 if cmd_tokens[0] == 'list': 316 if cmd_tokens[0] == 'list':
335 beinc_prnt('--- Targets ---') 317 beinc_prnt('--- Targets ---')
336 for target in target_list: 318 for target in target_list:
@@ -360,17 +342,14 @@ def beinc_cmd_target_handler(cmd_tokens):
360 break 342 break
361 else: 343 else:
362 beinc_prnt('no matching target for "{0}"'.format(name)) 344 beinc_prnt('no matching target for "{0}"'.format(name))
363
364 return weechat.WEECHAT_RC_OK 345 return weechat.WEECHAT_RC_OK
365 346
366 347
367def beinc_command(data, buffer_obj, args): 348def beinc_command(data, buffer_obj, args):
368 global enabled 349 global enabled
369 cmd_tokens = args.split() 350 cmd_tokens = args.split()
370
371 if not cmd_tokens: 351 if not cmd_tokens:
372 return weechat.WEECHAT_RC_OK 352 return weechat.WEECHAT_RC_OK
373
374 if args == 'on': 353 if args == 'on':
375 enabled = True 354 enabled = True
376 beinc_prnt('BEINC on') 355 beinc_prnt('BEINC on')
@@ -387,17 +366,14 @@ def beinc_command(data, buffer_obj, args):
387 str(data), 366 str(data),
388 str(cmd_tokens), 367 str(cmd_tokens),
389 str(args))) 368 str(args)))
390
391 return weechat.WEECHAT_RC_OK 369 return weechat.WEECHAT_RC_OK
392 370
393 371
394def beinc_privmsg_handler(data, signal, signal_data): 372def beinc_privmsg_handler(data, signal, signal_data):
395 if not enabled: 373 if not enabled:
396 return weechat.WEECHAT_RC_OK 374 return weechat.WEECHAT_RC_OK
397
398 prvmsg_dict = weechat.info_get_hashtable('irc_message_parse', 375 prvmsg_dict = weechat.info_get_hashtable('irc_message_parse',
399 {'message': signal_data }) 376 {'message': signal_data})
400
401 # packing the privmsg handler values 377 # packing the privmsg handler values
402 ph_values = dict() 378 ph_values = dict()
403 ph_values['server'] = signal.split(',')[0] 379 ph_values['server'] = signal.split(',')[0]
@@ -406,70 +382,75 @@ def beinc_privmsg_handler(data, signal, signal_data):
406 ph_values['source_nick'] = prvmsg_dict['nick'] 382 ph_values['source_nick'] = prvmsg_dict['nick']
407 ph_values['message'] = ':'.join( 383 ph_values['message'] = ':'.join(
408 prvmsg_dict['arguments'].split(':')[1:]).strip() 384 prvmsg_dict['arguments'].split(':')[1:]).strip()
409
410 if ph_values['channel'] == ph_values['own_nick']: 385 if ph_values['channel'] == ph_values['own_nick']:
411 # priv messages are handled here 386 # priv messages are handled here
412 if not global_values['global_private_messages_policy']: 387 if not global_values['global_private_messages_policy']:
413 return weechat.WEECHAT_RC_OK 388 return weechat.WEECHAT_RC_OK
414 389 p_messages_policy = global_values['global_private_messages_policy']
415 if global_values['global_private_messages_policy'] == BEINC_POLICY_LIST_ONLY \ 390 if p_messages_policy == BEINC_POLICY_LIST_ONLY and
416 and '{0}.{1}'.format( 391 '{0}.{1}'.format(
417 ph_values['server'], 392 ph_values['server'],
418 ph_values['source_nick'].lower()) not in global_values['global_nicks']: 393 ph_values['source_nick'].lower()
394 ) not in global_values['global_nicks']:
419 return weechat.WEECHAT_RC_OK 395 return weechat.WEECHAT_RC_OK
420
421 for target in target_list: 396 for target in target_list:
422 if not target.enabled: 397 if not target.enabled:
423 continue 398 continue
424 if target.private_messages_policy == BEINC_POLICY_ALL or ( 399 if target.private_messages_policy == BEINC_POLICY_ALL or
425 target.private_messages_policy == BEINC_POLICY_LIST_ONLY \ 400 (
426 and '{0}.{1}'.format( 401 target.private_messages_policy == BEINC_POLICY_LIST_ONLY and
427 ph_values['server'], 402 '{0}.{1}'.format(
428 ph_values['source_nick'].lower()) in target.nicks): 403 ph_values['server'],
404 ph_values['source_nick'].lower()) in target.nicks
405 ):
429 target.send_private_message_notification(ph_values) 406 target.send_private_message_notification(ph_values)
430 407 elif ph_values['own_nick'].lower() in ph_values['message'].lower():
431 elif ph_values['own_nick'].lower() in ph_values['message'].lower():
432 # notify messages are handled here 408 # notify messages are handled here
433 if not global_values['global_notifications_policy']: 409 if not global_values['global_notifications_policy']:
434 return weechat.WEECHAT_RC_OK 410 return weechat.WEECHAT_RC_OK
435 411 notifications_policy = global_values['global_notifications_policy']
436 if global_values['global_notifications_policy'] == BEINC_POLICY_LIST_ONLY \ 412 if notifications_policy == BEINC_POLICY_LIST_ONLY and
437 and '{0}.{1}'.format( 413 (
438 ph_values['server'], 414 '{0}.{1}'.format(
439 ph_values['channel'].lower()) not in global_values['global_chans']: 415 ph_values['server'],
416 ph_values['channel'].lower()
417 ) not in global_values['global_chans']
418 ):
440 return weechat.WEECHAT_RC_OK 419 return weechat.WEECHAT_RC_OK
441
442 for target in target_list: 420 for target in target_list:
443 if not target.enabled: 421 if not target.enabled:
444 continue 422 continue
445 if target.notifications_policy == BEINC_POLICY_ALL or ( 423 if target.notifications_policy == BEINC_POLICY_ALL or (
446 target.notifications_policy == BEINC_POLICY_LIST_ONLY \ 424 target.notifications_policy == BEINC_POLICY_LIST_ONLY and
447 and '{0}.{1}'.format( 425 '{0}.{1}'.format(
448 ph_values['server'], 426 ph_values['server'],
449 ph_values['channel'].lower()) in target.chans): 427 ph_values['channel'].lower()) in target.chans
428 ):
450 target.send_notify_message_notification(ph_values) 429 target.send_notify_message_notification(ph_values)
451 430 elif global_values['global_channel_messages_policy']:
452 elif global_values['global_channel_messages_policy']:
453 # chan messages are handled here 431 # chan messages are handled here
454 if not global_values['global_notifications_policy']: 432 if not global_values['global_notifications_policy']:
455 return weechat.WEECHAT_RC_OK 433 return weechat.WEECHAT_RC_OK
456 434 c_messages_policy = global_values['global_channel_messages_policy']
457 if global_values['global_channel_messages_policy'] == BEINC_POLICY_LIST_ONLY \ 435 if c_messages_policy == BEINC_POLICY_LIST_ONLY and
458 and '{0}.{1}'.format( 436 (
459 ph_values['server'], 437 '{0}.{1}'.format(
460 ph_values['channel'].lower()) not in global_values['global_chans']: 438 ph_values['server'],
439 ph_values['channel'].lower()
440 ) not in global_values['global_chans']
441 ):
461 return weechat.WEECHAT_RC_OK 442 return weechat.WEECHAT_RC_OK
462
463 for target in target_list: 443 for target in target_list:
464 if not target.enabled: 444 if not target.enabled:
465 continue 445 continue
466 if target.channel_messages_policy == BEINC_POLICY_ALL or ( 446 if target.channel_messages_policy == BEINC_POLICY_ALL or
467 target.channel_messages_policy == BEINC_POLICY_LIST_ONLY \ 447 (
468 and '{0}.{1}'.format( 448 target.channel_messages_policy == BEINC_POLICY_LIST_ONLY and
469 ph_values['server'], 449 '{0}.{1}'.format(
470 ph_values['channel'].lower()) in target.chans): 450 ph_values['server'],
451 ph_values['channel'].lower()) in target.chans
452 ):
471 target.send_channel_message_notification(ph_values) 453 target.send_channel_message_notification(ph_values)
472
473 return weechat.WEECHAT_RC_OK 454 return weechat.WEECHAT_RC_OK
474 455
475 456
@@ -484,7 +465,6 @@ def beinc_init():
484 global_values['global_chans'] = set() 465 global_values['global_chans'] = set()
485 global_values['global_nicks'] = set() 466 global_values['global_nicks'] = set()
486 target_list = list() 467 target_list = list()
487
488 custom_error = '' 468 custom_error = ''
489 global_values['global_channel_messages_policy'] = False 469 global_values['global_channel_messages_policy'] = False
490 global_values['global_private_messages_policy'] = False 470 global_values['global_private_messages_policy'] = False
@@ -496,14 +476,13 @@ def beinc_init():
496 weechat.info_get('weechat_dir', ''), 476 weechat.info_get('weechat_dir', ''),
497 'beinc.json') 477 'beinc.json')
498 beinc_prnt('Parsing {0}...'.format(beinc_config_file_str)) 478 beinc_prnt('Parsing {0}...'.format(beinc_config_file_str))
499
500 custom_error = 'load error' 479 custom_error = 'load error'
501 with open(beinc_config_file_str, 'r') as fp: 480 with open(beinc_config_file_str, 'r') as fp:
502 config_dict = json.load(fp) 481 config_dict = json.load(fp)
503
504 custom_error = 'target parse error' 482 custom_error = 'target parse error'
505 global_values['use_current_buffer'] = bool(config_dict['irc_client'].get( 483 global_values['use_current_buffer'] = bool(
506 'use_current_buffer', False)) 484 config_dict['irc_client'].get(
485 'use_current_buffer', False))
507 for target in config_dict['irc_client']['targets']: 486 for target in config_dict['irc_client']['targets']:
508 try: 487 try:
509 new_target = WeechatTarget(target) 488 new_target = WeechatTarget(target)
@@ -518,32 +497,27 @@ def beinc_init():
518 global_values['global_private_messages_policy'] = True 497 global_values['global_private_messages_policy'] = True
519 if new_target.notifications_policy: 498 if new_target.notifications_policy:
520 global_values['global_notifications_policy'] = True 499 global_values['global_notifications_policy'] = True
521
522 target_list.append(new_target) 500 target_list.append(new_target)
523 beinc_prnt('BEINC target "{0}" added'.format(new_target.name)) 501 beinc_prnt('BEINC target "{0}" added'.format(new_target.name))
524
525 beinc_prnt('Done!') 502 beinc_prnt('Done!')
526
527 except Exception as e: 503 except Exception as e:
528 beinc_prnt('ERROR: unable to parse {0}: {1} - {2}'.format( 504 beinc_prnt('ERROR: unable to parse {0}: {1} - {2}'.format(
529 beinc_config_file_str, custom_error, e)) 505 beinc_config_file_str, custom_error, e))
530 enabled = False 506 enabled = False
531
532 # do not return error / exit the script 507 # do not return error / exit the script
533 # in order to give a smoother opportunity to fix a 'broken' config 508 # in order to give a smoother opportunity to fix a 'broken' config
534 return weechat.WEECHAT_RC_OK 509 return weechat.WEECHAT_RC_OK
535
536 return weechat.WEECHAT_RC_OK 510 return weechat.WEECHAT_RC_OK
537 511
538 512
539 513weechat.register(
540weechat.register('beinc_weechat', 514 'beinc_weechat',
541 'Simeon Simeonov', 515 'Simeon Simeonov',
542 '1.0', 516 '1.0',
543 'GPL3', 517 'GPL3',
544 'Blackmore\'s Extended IRC Notification Collection (Weechat Client)', 518 'Blackmore\'s Extended IRC Notification Collection (Weechat Client)',
545 '', 519 '',
546 '') 520 '')
547version = weechat.info_get('version_number', '') or 0 521version = weechat.info_get('version_number', '') or 0
548if int(version) < 0x00040000: 522if int(version) < 0x00040000:
549 weechat.prnt('', 'WeeChat version >= 0.4.0 is required to run beinc') 523 weechat.prnt('', 'WeeChat version >= 0.4.0 is required to run beinc')