This module provide network grep plugin Example of usage from jabber c

 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
"""
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 processor import Processor
from decorators import simple_named_processor
SIZE_LIMIT = 500 * 1024
LINES_LIMIT = 3
is_valid_url(url):
"""
Test the url on validness.
"""
parts = urlsplit(url)
if not parts[0].startswith('http'):
return False
if not parts[1]:
return False
return True
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)
lines = []
data = Popen(["lynx", "-dump", url], stdout=PIPE).communicate()[0]
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):
if not text:
return 'empty text'#None
try:
pattern, url = text.rsplit(' ', 1)
except ValueError:
return 'can\'t split your message with space'#None
if not is_valid_url(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)
msg = '%s\n%s' % (frm, '\n'.join(lines))
return msg