-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.py
130 lines (92 loc) · 2.68 KB
/
server.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import zmq
import shelve
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
# HTTP #
httpd = None
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
channel_name = self.path[1:]
if channel_name == '':
self.send_response(302)
self.send_header('Location', 'https://tingbot-python.readthedocs.io/en/latest/webhooks.html')
return
html = html_template().format(
channel=channel_name,
channel_value=db_get(channel_name))
self.send_response(200)
self.end_headers()
self.request.sendall(html)
def do_POST(self):
channel_name = self.path[1:]
content_length = int(self.headers['Content-Length'])
if content_length > 1024:
self.send_error(413)
return
data = self.rfile.read(content_length)
channel_send(channel_name, data)
self.send_response(200)
self.end_headers()
self.request.sendall(b'OK')
def http_setup():
global httpd
bind_address = ('0.0.0.0', 20451)
httpd = HTTPServer(bind_address, Handler)
httpd.timeout = 0
def http_loop():
httpd.handle_request()
_html_template = None
def html_template():
global _html_template
_html_template = None # TODO: remove
if _html_template is None:
with open('get.html') as f:
_html_template = f.read()
return _html_template
# ZMQ #
zmq_socket = None
def zmq_setup():
global zmq_socket
context = zmq.Context()
zmq_socket = context.socket(zmq.XPUB)
zmq_socket.setsockopt(zmq.XPUB_VERBOSE, 1)
zmq_socket.bind('tcp://*:20452')
def zmq_send(channel, msg):
zmq_socket.send_multipart((channel, msg))
# DB #
store = None
def db_setup():
global store
store = shelve.open('db.shelve')
def db_store(channel, value):
store[channel] = value
def db_get(channel):
try:
return store[channel]
except KeyError:
return None
# MAIN #
def main():
http_setup()
zmq_setup()
db_setup()
run_loop()
def run_loop():
while True:
http_loop()
rlist, _, _ = zmq.select([httpd, zmq_socket], [], [])
if zmq_socket in rlist:
new_subscriber()
def new_subscriber():
event = zmq_socket.recv()
# Event is one byte 0=unsub or 1=sub, followed by topic
if event[0] == b'\x01':
topic = event[1:]
cached_value = db_get(topic)
if cached_value is not None:
print ("Sending cached topic %s" % topic)
zmq_socket.send_multipart([topic, cached_value])
def channel_send(channel, msg):
db_store(channel, msg)
zmq_send(channel, msg)
if __name__ == '__main__':
main()