-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.py
241 lines (213 loc) · 7.66 KB
/
app.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
import json
import tornado.ioloop
import tornado.web
import tornado.auth
import tornado.escape
import tornado.log
from tornado.web import RequestHandler
from motorengine import connect
from auth import GithubMixin2
import db
import options
from log import logger
import argparse
from version import BackendVersion
from sig import recover_address
parser = argparse.ArgumentParser(
description='Welcome to Dweb World')
parser.add_argument(
'-p', '--port',
dest='port',
action='store',
type=int,
default=options.port,
help='run on the given port'
)
args = parser.parse_args()
class JsonHandler(RequestHandler):
def set_default_headers(self):
self.set_header('Content-Type', 'application/json')
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers', '*')
self.set_header('Access-Control-Allow-Methods', '*')
def options(self):
pass
class ProxyHandler(JsonHandler, GithubMixin2):
async def get(self):
code = self.get_argument('code', None)
client_id = self.get_argument('client_id', None)
if not client_id or client_id not in options.d_auth:
self.write({'error': 'wrong client_id'})
return
params = {
'client_id': client_id,
'client_secret': options.d_auth[client_id],
'code': code,
# TODO: add state as param
}
ret = await self.get_authenticated_user(**params)
ret = codecs.decode(ret, 'ascii')
ret = json.loads(ret)
self.write(ret)
class ShareHandler(JsonHandler):
async def post(self):
token = self.request.headers['Authorization'][6:]
d = tornado.escape.json_decode(self.request.body)
if 'tags' in d and isinstance(d['tags'], str):
d['tags'] = [tag.strip() for tag in d['tags'].strip().split(',')]
if 'miner_ids' in d:
miner_ids = d['miner_ids'].strip().split(',')
d['miner_ids'] = [i.strip() for i in miner_ids if i.strip()]
share = await db.add_share(d, token)
if hasattr(share, '_values'):
ret = {'data': share._values}
else:
ret = {'error': str(share)}
self.write(ret)
class AddMetaHandler(JsonHandler):
async def post(self):
previous_path = self.get_argument("previous_path", '')
if previous_path:
self.write({'error': 'please use edit_meta'})
return
authed = True
if 'authorization' not in self.request.headers:
authed = False
else:
token = self.request.headers['authorization'].split()[-1][2:]
address = self.request.headers['address']
_address = recover_address(token)
logger.warning('no Authorization, wrong sig {} {}'.format(_address, address))
if _address.lower() != address.lower():
authed = False
if not authed:
logger.warning('no Authorization')
self.write({'error': 'no Authorization'})
return
path = self.get_argument("path", '')
eth = self.get_argument("eth", '')
name = self.get_argument("name", '')
image = self.get_argument("image", '')
tags = self.get_argument("tags", '')
authors = self.get_argument("authors", '')
if not path:
logger.info(self.request.body)
d = json.loads(self.request.body.decode('u8'))
path = d.get('path')
eth = d.get('eth')
name = d.get('name')
image = d.get('image')
tags = d.get('tags')
authors = d.get('authors')
if not path:
self.write({'error': 'server got no data'})
return
tags = tags.strip().split()
meta = await db.add_meta(path, eth, name, image, tags, authors)
print(dir(meta))
if hasattr(meta, '_values') and meta._values:
ret = {'data': meta._values}
else:
ret = {'error': str(meta)}
self.write(ret)
async def get(self):
return await self.post()
class EditMetaHandler(JsonHandler):
async def post(self):
authed = True
if 'authorization' not in self.request.headers:
authed = False
else:
token = self.request.headers['authorization'].split()[-1][2:]
address = self.request.headers['address']
_address = recover_address(token)
logger.warning('no Authorization, wrong sig {} {}'.format(_address, address))
if _address.lower() != address.lower():
authed = False
if not authed:
logger.warning('no Authorization')
self.write({'error': 'no Authorization'})
return
previous_path = self.get_argument("previous_path", '')
path = self.get_argument("path", '')
eth = self.get_argument("eth", '')
name = self.get_argument("name", '')
image = self.get_argument("image", '')
tags = self.get_argument("tags", '')
authors = self.get_argument("authors", '')
if not path:
d = json.loads(self.request.body.decode('u8'))
previous_path = d.get('previous_path')
path = d.get('path')
eth = d.get('eth')
name = d.get('name')
image = d.get('image')
tags = d.get('tags')
authors = d.get('authors')
if not path or not previous_path:
self.write({'error': 'server got no data'})
return
tags = tags.strip().split()
meta = await db.edit_meta(previous_path, path, eth, name, image, tags, authors)
if hasattr(meta, '_values') and meta._values:
ret = {'data': meta._values}
else:
ret = {'error': str(meta)}
self.write(ret)
async def get(self):
return await self.post()
class GetMetaHandler(JsonHandler):
async def get(self):
eth = self.get_argument("eth", '')
tag = self.get_argument("tag", '')
if not eth and not tag:
self.write({'error': 'no path'})
return
docs = await db.get_meta(eth, tag)
ret = {'data': docs}
self.write(ret)
class SearchHandler(JsonHandler):
async def get(self):
question = self.get_argument("question", '')
ret = {}
ret['version'] = 'https://jsonfeed.org/version/1'
ret['title'] = 'Search Results of: {}'.format(question)
if question:
ret['items'] = await db.search_shares(question)
else:
ret['error'] = 'no question'
print(ret)
self.write(ret)
class SharesHandler(JsonHandler):
async def get(self):
shares = await db.get_shares()
l_shares = []
for share in shares:
l_shares.append(dict(share._values))
ret = {'data': l_shares}
self.write(ret)
class VersionHandler(JsonHandler):
async def get(self):
ret = {'version': BackendVersion}
self.write(ret)
def make_app():
return tornado.web.Application([
(r"/proxy", ProxyHandler),
(r"/share", ShareHandler),
(r"/shares", SharesHandler),
(r"/search", SearchHandler),
(r"/add_meta", AddMetaHandler),
(r"/edit_meta", EditMetaHandler),
(r"/get_meta", GetMetaHandler),
(r"/version", VersionHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(args.port)
logger.info('Server started on %s' % args.port)
io_loop = tornado.ioloop.IOLoop.instance()
connect("test2", host="localhost", port=27017, io_loop=io_loop)
io_loop.start()