-
Notifications
You must be signed in to change notification settings - Fork 2
/
polling.py
89 lines (73 loc) · 2.69 KB
/
polling.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
77
78
79
80
81
82
83
84
85
86
87
88
89
import threading
import sys
PYTHON_VERSION = sys.version_info[0]
if PYTHON_VERSION >= 3:
import urllib.parse as urlparse
import http.server as BaseHTTPServer
else:
import urlparse
import BaseHTTPServer
import json
import socket
try:
import Queue as queue
except ImportError:
import queue
class Server(BaseHTTPServer.HTTPServer):
def __init__(self,smsq,config,*a,**kw):
self.smsq = smsq
self.config = config
BaseHTTPServer.HTTPServer.__init__(self,*a,**kw)
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
def end_headers(self):
self.send_header("Cache-Control","no-cache, must-revalidate")
self.send_header("Pragma","no-cache")
self.send_header("Expires","Tue, 5 Jan 1988 05:00:00 GMT")
self.send_header('Content-type','application/json')
BaseHTTPServer.BaseHTTPRequestHandler.end_headers(self)
def do_GET(self):
sms = None
if self.server.config.get('secret'):
q = urlparse.parse_qs(urlparse.urlparse( self.path ).query)
secret = q.get('secret')
if (self.server.config.get('secret') != secret[0]):
self.send_response(403)
self.end_headers()
try:
sms = self.server.smsq.get(timeout=25)
self.server.smsq.task_done()
self.send_response(200)
self.end_headers()
self.wfile.write(bytes(json.dumps(sms)))
except queue.Empty:
self.send_response(204)
self.end_headers()
self.wfile.write(b"[]")
except socket.timeout as e:
raise e
class Client(threading.Thread):
def __init__(self, smsq, url,secret=None, *a,**kw):
self.smsq = smsq
if secret:
self.request = url + "?secret=" + secret
else:
self.request = url
return super(Client,self).__init__(*a,**kw)
def run(self):
while True:
try:
response = urllib2.urlopen(self.request, timeout=30).read().decode('utf-8')
except:
response = '[]'
if response:
try:
sms = json.loads(response)
self.smsq.put(sms)
except json.decoder.JSONDecodeError:
logging.error('bad data from '+self.request)
def new(smsq, config):
server_address = ('', config['polling_port'])
server = Server(smsq, config, server_address, Handler)
httpd = threading.Thread(target=server.serve_forever)
httpd.daemon = True
return httpd