-
Notifications
You must be signed in to change notification settings - Fork 0
/
receiver.py
76 lines (61 loc) · 1.86 KB
/
receiver.py
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
#!/usr/bin/env python
import pika
import time
import md5
import sys
import os
from utils import *
class Receiver:
#
# Initialize connections and database
#
def __init__(self,index):
self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
self.channel = self.connection.channel()
self.channel.queue_declare(queue='requests', durable=True) #queue for receiving requests
self.channel.queue_declare(queue='responses', durable=True) #queue for sending responses
self.initDB(index)
#
# Initialize local database. Or do nothing if it already exists.
#
def initDB(self,index):
self.dbname = 'DB' + index
dirs = os.listdir('.')
for d in dirs:
if self.dbname in d:
return
os.mkdir('./'+self.dbname)
#
# Get and save a screenshot from the given url.
#
def saveScreenshot(self,url):
os.system('gnome-web-photo -t 0 --mode=photo %s %s/%s 2> out && rm out' % (url,self.dbname,md5.new(url).hexdigest()))
return True
#
# Parse messages from the 'requests' queue, forwarding the work to 'saveScreenshot' method.
#
def work(self):
def callback(ch, method, properties, msgbody):
msg = eval(msgbody)
print " [x] Received: "
printmsg(msg)
mymsg = {}
mymsg[TYPE] = RES_SCREENSHOT_ACK
mymsg[SUCCESS] = self.saveScreenshot(msg[URL])
mymsg[ID] = os.getcwd()+'/'+self.dbname
self.channel.basic_publish(exchange='', routing_key='responses', body=str(mymsg),properties=pika.BasicProperties(delivery_mode = 2,))
print " [x] Push to queue = 'responses':"
printmsg(mymsg)
ch.basic_ack(delivery_tag = method.delivery_tag)
self.channel.basic_qos(prefetch_count=1)
self.channel.basic_consume(callback, queue='requests')
self.channel.start_consuming()
rcv = None
def __main__():
global rcv
rcv = Receiver(sys.argv[1])
rcv.work()
try:
__main__()
except KeyboardInterrupt:
rcv.connection.close()