-
Notifications
You must be signed in to change notification settings - Fork 3
/
api.py
executable file
·278 lines (239 loc) · 8.56 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
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#!/usr/bin/env python
import sys, os
abspath = os.path.dirname(__file__)
sys.path.append(abspath)
os.chdir(abspath)
import logging
import json
import lib.misc
import web
import mimerender
import paythru
import yaml
routeconfigpath = 'config/routes.yaml'
routeconfig = yaml.load(file(routeconfigpath))
appconfigpath = routeconfig['appconfigpath']
URISEPARATOR = '/'
pt = paythru.Paythru(appconfigpath)
# pt.emailtemplateconfig = templateconfig['emails']
googleanalyticsid = pt.googleanalyticsid
logger = logging.getLogger(__name__)
templateconfig = routeconfig['templates']
render_json = lambda **args: json.dumps(args)
site_template = web.template.render(templateconfig['pages']['dirpath'], base=templateconfig['pages']['base'])
api_template = web.template.render(templateconfig['endpoints']['dirpath'])
html_template = web.template.render(templateconfig['endpoints']['dirpath'], base=templateconfig['endpoints']['base'])
mimerender = mimerender.WebPyMimeRender()
app = web.application(fvars=globals(), autoreload=False)
for item in routeconfig['routes']:
app.add_mapping(item['route'], item['class'])
application = app.wsgifunc()
"""
def gettag(uristring, routedict):
resolvedtag = None
for tag in routedict.keys():
if uristring.endswith(URISEPARATOR + tag):
resolvedtag = routedict[tag]
break
return resolvedtag
"""
def scaffolding(rawuri):
inputuri = rawuri
"""
currency = gettag(rawuri, routeconfig['currencies'])
if currency:
inputuri = uristring[:-1 * len(URISEPARATOR + currency)]
"""
try:
pt.setUri(lib.misc.urldecode(inputuri))
if pt.forceredirect and inputuri != pt.getUri():
redirecturl = URISEPARATOR + lib.misc.urlencode(pt.getUri())
#if currency: redirecturl += URISEPARATOR + currency
logger.info('%s is not canonical. Redirecting to %s', inputuri, redirecturl)
logRequest('301:' + redirecturl)
raise web.redirect(redirecturl)
except NotImplementedError, e:
logRequest('404:' + str(e))
raise web.notfound()
except RuntimeError, e:
logRequest('400:' + str(e))
raise web.badrequest()
except web.Redirect, e:
logger.info(str(e))
raise
except Exception, e:
logger.warn('Exception type: %s', type(e).__name__)
raise
logger.info('Scaffolding complete')
return pt
def notfound():
return web.notfound(site_template.notfound(pt.hostname, pt.appconfig['sitename'], googleanalyticsid))
app.notfound = notfound
def badrequest():
return web.badrequest(site_template.badrequest(pt.hostname, pt.appconfig['sitename'], googleanalyticsid))
app.badrequest = badrequest
def logRequest(result = None):
pt.logRequest(web.ctx['ip'], web.ctx['fullpath'], web.ctx['method'], result)
class index:
def GET(self):
logRequest()
return site_template.index(pt.hostname, pt.appconfig['sitename'], googleanalyticsid)
class about:
def GET(self):
logRequest()
return site_template.about(pt.hostname, pt.appconfig['sitename'], googleanalyticsid)
class developers:
def GET(self):
logRequest()
return site_template.developers(pt.hostname, pt.appconfig['sitename'], googleanalyticsid)
class faq:
def GET(self):
logRequest()
return site_template.faq(pt.hostname, pt.appconfig['sitename'], googleanalyticsid)
class smsmessage:
@mimerender(
default = 'json',
json = render_json
)
def POST(self):
logger.info('Received %s to %s from %s. Attempting to update.', web.ctx['method'], web.ctx['fullpath'], web.ctx['ip'])
postdata = web.input()
try:
pt.handlesms(postdata)
except Exception as e:
logger.error(e)
raise badrequest()
return {'status': 200}
def GET(self):
return 'Endpoint works :D'
class blocknotification:
@mimerender(
default = 'json',
json = render_json
)
def POST(self):
logger.info('Received %s to %s from %s. Attempting to update.', web.ctx['method'], web.ctx['fullpath'], web.ctx['ip'])
postdata = web.data()
#logger.debug('postdata: %s', postdata)
jsonbody = None
try:
if postdata:
jsonbody = json.loads(postdata)
except Exception as e:
logger.error(e)
raise badrequest()
if jsonbody and 'USD' in jsonbody and '24h' in jsonbody['USD']:
pt.setprice(jsonbody['USD']['24h'])
"""
if jsonbody and 'tx' in jsonbody:
pt.notifyuritransactions(jsonbody)"""
if pt.transactionmaxageblocks >= 0:
pt.handleunclaimedfunds(pt.transactionmaxageblocks)
return {'status': 200}
def GET(self):
return 'Endpoint works :D'
class claim:
def __init__(self):
logger.info('claim called')
@mimerender(
default = 'html',
html = html_template.claim
)
def GET(self, rawuri, authcode = None):
if authcode and authcode.startswith('/'):
authcode = authcode[len('/'):]
scaffolding(rawuri)
po = pt.getCurrentBestAddress()
result = {
'hostname': pt.hostname,
'sitename': pt.appconfig['sitename'],
'googleanalyticsid': googleanalyticsid,
'address': po.address,
'uri': po.uri,
'addressstatus': po.status,
'authcode': authcode
}
logRequest('200:' + str(result))
return result
@mimerender(
default = 'html',
html = html_template.claim
)
def POST(self, rawuri, authcode = None):
resultmsg = 'Unable to complete your request'
scaffolding(rawuri)
i = web.input(newaddress = None)
logger.info('POST input: %s', str(i))
try:
if i.newaddress and i.authcode:
# NOTE this is a good entrypoint into a theorhetical pt.upsertNamecoinAlias()
if pt.updateNotification(i.authcode, i.newaddress):
resultmsg = 'Updated Bitcoin address for this page.'
else:
i.newaddress = ''
resultmsg = 'Could not update address on this page. Is your authcode correct? Get a new one by pressing the button at the bottom of this page.'
except RuntimeError, e:
resultmsg = 'Could not update Bitcoin address: ' + str(e)
logger.info(resultmsg)
po = pt.getCurrentBestAddress()
result = {
'hostname': pt.hostname,
'sitename': pt.appconfig['sitename'],
'googleanalyticsid': googleanalyticsid,
'address': po.address,
'uri': po.uri,
'addressstatus': po.status,
'resultmsg': resultmsg
}
logRequest('200:' + str(result))
return result
class getaddress:
def __init__(self):
logger.info('getaddress called')
@mimerender(
default = 'html',
json = api_template.jsonresponse,
txt = api_template.plaintext,
html = html_template.getaddress,
xml = api_template.xmlresponse
)
def GET(self, rawuri):
# this is strictly for debug
if rawuri == 'localhost':
return {
'sitename': pt.appconfig['sitename'],
'hostname': pt.appconfig['hostname'],
'googleanalyticsid': pt.appconfig['googleanalyticsid'],
'address': '1LoCALHoSTxxxxxxxxxxxxxxxxxxxxxxxx',
'uri': 'localhost',
'addressstatus': '1',
'btcusd': 1
}
# try:
scaffolding(rawuri)
logger.info('pt.resolveduri = %s', pt.resolveduri)
po = pt.getCurrentBestAddress()
prices = pt.getprice()
result = {
'sitename': pt.appconfig['sitename'],
'hostname': pt.appconfig['hostname'],
'googleanalyticsid': googleanalyticsid,
'address': po.address,
'uri': po.uri,
'addressstatus': po.status,
'btcusd': prices['BTCUSD']
}
logRequest('200:' + str(result))
return result
# except Exception, e:
# logger.exception(str(e))
# raise web.internalerror()
def POST(self, rawuri):
pt = scaffolding(rawuri)
claimresult = pt.tryClaimFunds()
#po = pt.getCurrentBestAddress()
redirecturl = '/' + lib.misc.urlencode(pt.getUri())
logRequest('301:' + redirecturl)
raise web.redirect(redirecturl)
if __name__ == "__main__":
app.run()