coding utf-8 This module provide network grep plugin Example of usage

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
# -*- coding: utf-8 -*-
"""
This module provide network grep plugin.
Example of usage from jabber client:
!grep One two three http://domain.com
"""
import urllib
from subprocess import Popen, PIPE
import sys
import re
from urlparse import urlsplit
import locale
from processor import Processor
from decorators import simple_named_processor
SIZE_LIMIT = 500 * 1024
LINES_LIMIT = 3
def normalize_url(url):
"""
Try to make valid url.
"""
if not url.startswith('http://'):
return 'http://' + url
else:
return url
class HookException(Exception):
pass
def hook(chunk, chunk_size, total_size):
raise HookException(total_size)
def get_size(url):
"""
Detect size of remote file.
"""
try:
urllib.urlretrieve(url, reporthook=hook)
except HookException, ex:
return ex.message
def grep(pattern, url, limit=3):
"""
Find lines that matches the pattern in the contents of page with given url.
"""
re_pattern = re.compile(re.escape(pattern), re.I|re.U)
lines = []
data = Popen(["lynx", "-dump", url], stdout=PIPE).communicate()[0]
data = data.decode('utf-8')
for line in data.splitlines():
if re_pattern.search(line):
lines.append(line)
if len(lines) == limit:
break
return lines
class GrepProcessor(Processor):
protocol = 'all' #protocol name
lowLevel = 0 # 1 if lowlevel for protocol
@simple_named_processor('grep')
def process(self, frm, text):
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
if not text:
return 'empty text'#None
try:
pattern, url = text.rsplit(' ', 1)
except ValueError:
return 'can\'t split your message with space'#None
try:
url = normalize_url(url)
if not url:
msg = '%s, bad url' % frm
else:
size = get_size(url)
if size > SIZE_LIMIT:
msg = '%s, file size > %d' % (frm, SIZE_LIMIT)
else:
lines = grep(pattern, url, LINES_LIMIT)
if lines:
data = '\n ' + '\n'.join(lines)
else:
data = 'no results'
msg = '%s, %s' % (frm, data)
except IOError, ex:
msg = u'%s, %s' % (frm, ex[1][1].decode('UTF-8'))
return msg