summaryrefslogtreecommitdiff
path: root/beinc_weechat.py
diff options
context:
space:
mode:
authorSimeon Simeonov2014-05-08 10:25:39 +0200
committerSimeon Simeonov2014-05-08 10:25:39 +0200
commite4e15e7f4e594efc899016ba17cabd02fa344600 (patch)
treea90786c2a56c288c0e0f541f6b9a1f0c81dedec5 /beinc_weechat.py
parent60f47b04174d016cc86c6e06fdaf0794c3d14216 (diff)
Forcing PEP8 compatibility
Diffstat (limited to 'beinc_weechat.py')
-rw-r--r--beinc_weechat.py202
1 files changed, 88 insertions, 114 deletions
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')