-
Notifications
You must be signed in to change notification settings - Fork 1
/
web.py
206 lines (150 loc) · 5.33 KB
/
web.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import asyncio
import datetime
import json
import os
import re
import aiohttp
from aiohttp import web
from functools import wraps
import triggers
from util import JSONResponse, ErrorResponse, CappedCache
CLIENT_SECRET = os.environ.get('CLIENT_SECRET', '')
STATUS_URL = 'https://congress.api.sunlightfoundation.com'
cache = CappedCache(max_size=1000)
@asyncio.coroutine
def data_middleware(app, handler):
@asyncio.coroutine
def middleware(request):
try:
request.data = yield from request.json()
except ValueError:
request.data = {}
return (yield from handler(request))
return middleware
@asyncio.coroutine
def auth_middleware(app, handler):
@asyncio.coroutine
def middleware(request):
key = request.headers.get('IFTTT-Channel-Key', '')
if key == CLIENT_SECRET or not CLIENT_SECRET:
return (yield from handler(request))
msg = {
"errors": [
{"message": "Unauthorized. Always gotta be sneaking about, eh?"}
]
}
raise web.HTTPUnauthorized(
text=json.dumps(msg), content_type='application/json')
return middleware
@asyncio.coroutine
def status(request):
resp = yield from aiohttp.request('get', STATUS_URL)
if resp.status == 200:
msg = "We just checked our Congress API's status and it's fine."
else:
msg = "Our API seems unavailable right now."
data = {
"status": "OK" if resp.status == 200 else "UNAVAILABLE",
"time": datetime.date.today().isoformat(),
"message": msg,
}
return JSONResponse(data)
@asyncio.coroutine
def test_setup(request):
data = {
"samples": {
"triggers": {
"new-bills-query": {
"query": "\"Common Core\""
},
"new-legislators": {
"location": {
"lat": 44.967586,
"lng": -103.772234,
"address": "19424 Us Highway 85, Belle Fourche, SD 57717",
"description": "Geographic Center of the United States"
}
}
}
}
}
return JSONResponse(data)
@asyncio.coroutine
def trigger(request):
name = request.match_info['trigger'].replace('-', '_')
handler = getattr(triggers, name, None)
if not handler:
msg = 'No such trigger: {}'.format(name)
raise web.HTTPInternalServerError(text=msg)
cache_key = handler.cache_key(request)
resp = cache.get(cache_key)
if resp:
resp = resp.copy()
else:
before = request.data.get('before')
after = request.data.get('after')
limit = request.data.get('limit')
if limit == 0:
return JSONResponse([])
trigger_fields = request.data.get('triggerFields') or {}
if handler.fields:
if not trigger_fields:
return ErrorResponse('triggerFields is required')
for field in handler.fields:
val = trigger_fields.get(field)
if handler.fields[field].required and not val:
return ErrorResponse('{} field is required'.format(field))
# dstr = json.dumps(trigger_fields, sort_keys=True)
# dstr = re.sub(r'[^a-zA-Z0-9]', '', dstr)
# key = '{}:{}'.format(name, dstr)
resp = yield from handler.check(trigger_fields, before, after, limit)
if isinstance(resp, JSONResponse):
cache.set(cache_key, resp, timeout=60)
return resp
@asyncio.coroutine
def options(request):
return web.Response(body=b"Hello, world")
@asyncio.coroutine
def validate(request):
name = request.match_info['trigger'].replace('-', '_')
field = request.match_info['field']
handler = getattr(triggers, name, None)
if not handler:
msg = 'No such trigger: {}'.format(name)
raise web.HTTPInternalServerError(text=msg)
if handler.fields and field in handler.fields:
val = request.data.get('value')
result = handler.fields[field].validate(val)
data = {'valid': result == True}
if result != True:
data['message'] = result
else:
data = {
'valid': False,
'message': 'No such field: {}'.format(field),
}
return web.Response(text=json.dumps({'data': data}),
content_type='application/json')
app = web.Application(middlewares=[auth_middleware, data_middleware])
app.router.add_route(
'GET', '/ifttt/v1/status', status)
app.router.add_route(
'POST', '/ifttt/v1/test/setup', test_setup)
app.router.add_route(
'POST', '/ifttt/v1/triggers/{trigger}', trigger)
app.router.add_route(
'POST', '/ifttt/v1/triggers/{trigger}/fields/{field}/options', options)
app.router.add_route(
'POST', '/ifttt/v1/triggers/{trigger}/fields/{field}/validate', validate)
if __name__ == '__main__':
PORT = os.environ.get('PORT', '8000')
if not CLIENT_SECRET:
print('!!! no client secret set, not checking auth.')
loop = asyncio.get_event_loop()
f = loop.create_server(app.make_handler(), '0.0.0.0', PORT)
srv = loop.run_until_complete(f)
print('serving on', srv.sockets[0].getsockname())
try:
loop.run_forever()
except KeyboardInterrupt:
pass