-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
96 lines (76 loc) · 3.24 KB
/
api.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
from twisted.web import http
from twisted.web.http import HTTPChannel
from twisted.internet import reactor
import threading
class BotHandler(http.Request, object):
def __init__(self, api, *args, **kwargs):
self.api = api
super(BotHandler, self).__init__(*args, **kwargs)
def render(self, content, headers):
for (header_name, header_value) in headers:
self.setHeader(header_name, header_value)
self.write(content)
self.finish()
def simple_render(self, content, content_type="text/plain"):
self.render(content, [("Content-Type", content_type)])
def not_found(self, message=None):
self.setResponseCode(404, message)
return self.simple_render("no no...")
def process(self):
command_args_list = [x for x in self.path.split("/") if x]
command = ""
args = []
if command_args_list:
command = command_args_list[0]
args = command_args_list[1:]
try:
if not command:
f = open("main.html")
content = f.read()
return self.simple_render(content, content_type="text/html")
if command.startswith("wave"):
n = int(args[0]) if len(args) > 0 else 1
if command == "wave_short":
self.api.trigger("wave", min=0.3, max=0.7, n=n)
elif command == "wave_quick":
self.api.trigger("wave", min=0.3, max=0.7, n=n, pause=0.2)
else:
self.api.trigger("wave", n=n)
return self.simple_render(" ".join(["Wave and smile."]*n))
elif command == "set":
self.api.trigger("set", position=float(args[0]))
return self.simple_render("ok")
elif command == "set_speed":
self.api.trigger("set_speed", position=float(args[0]))
return self.simple_render("ok")
except Exception, e:
return self.simple_render(e.message)
return self.not_found()
class BotHandlerFactory(object):
def __init__(self, api):
self.api = api
def __call__(self, *args, **kwargs):
return BotHandler(self.api, *args, **kwargs)
class StreamFactory(http.HTTPFactory):
protocol = HTTPChannel
class Api:
""" An api for attentionbot, uses a twisted server inside a thread to keep track of webby things. """
def __init__(self):
# This I believe is what you find when you look up "ugly" in the dictionary
# But I really don't want to try and understand this FactoryFactoryFactory stuff properly
HTTPChannel.requestFactory = BotHandlerFactory(api=self)
self.events = []
def demonize(self, port=8080):
reactor.listenTCP(port, StreamFactory())
t = threading.Thread(target=reactor.run)
t.daemon = True
t.start()
def run(self, port=8080):
reactor.listenTCP(port, StreamFactory())
reactor.run()
def trigger(self, event, **kwargs):
for x in range(len(self.events)):
if self.events[x][0] == event:
self.events[x] = (event, kwargs)
return
self.events.append((event, kwargs))