-
Notifications
You must be signed in to change notification settings - Fork 2
/
jsonif.py
285 lines (223 loc) · 7.7 KB
/
jsonif.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
279
280
281
282
283
284
#!/usr/bin/env python
# vim:fileencoding=utf-8:syntax=python:nomodified
# ninuXoo's JSON interface
import json
import time
from dbmanager import QueryMaker
from resources import Query
RESPONSE_OK = 200
RESPONSE_REQERROR = 400
RESPONSE_SERVERERROR = 500
RESPONSE_NOTIMPLEMENTED = 501
ERRORDICT = {
RESPONSE_OK: "OK",
RESPONSE_REQERROR: "Bad Request",
RESPONSE_SERVERERROR: "Server Error",
RESPONSE_NOTIMPLEMENTED: "Not Implemented"
}
class JSONError(Exception):
"JSON API generic error"
pass
class JSONSyntaxError(Exception):
"JSON syntax error"
pass
class Request(dict):
def __init__(self, requestdict = {}):
dict.__init__(self)
self.update(requestdict)
class JsonResponse(dict):
def __init__(self, responsen, description=None, responsedict = {}):
dict.__init__(self)
try:
dict.__setitem__(self, 'responsen', responsen)
if description:
dict.__setitem__(self, 'response', description)
else:
dict.__setitem__(self, 'response', ERRORDICT[responsen])
self.update(responsedict)
except Exception, e:
raise JSONError(str(e))
def dumps(self):
return json.dumps(self, skipkeys=True)
class JSONProcessor():
"Process JSON requests and return JSON responses, through the process() function"
def __init__(self):
try:
self.qm = QueryMaker('localhost','ninuu','ciaociao','ninuxuu') #FIXME
self.initialized = True
except Exception,e:
self.qm = None
self.initialized = False
def process(self, requestdict):
"select the appropriate handler for the request"
if not self.initialized:
response = JsonResponse(RESPONSE_SERVERERROR)
return response.dumps()
try:
req = Request(requestdict)
except Exception, e:
response = JsonResponse(RESPONSE_REQERROR, "Bad Request [%s]" % str(e))
return response.dumps()
if not req.has_key('op') or (req['op'] == ''):
response = JsonResponse(RESPONSE_REQERROR, "Bad Request [op field missing]")
return response.dumps()
# small python magic to call the method that has the same name of the request
if req['op'] in self.__class__.__dict__:
response = self.__class__.__dict__[req['op']](self, req)
else:
response = JsonResponse(RESPONSE_NOTIMPLEMENTED)
return response.dumps()
def resourcestats(self, request):
"return the number of resources indexed by the search engine"
try:
res = self.qm.getResourceStats()
response = JsonResponse(RESPONSE_OK, None, {'result': res})
except Exception, e:
response = JsonResponse(RESPONSE_SERVERERROR)
return response
def serverstats(self, request):
"return the number of servers indexed by the search engine"
try:
res = self.qm.getServerStats()
response = JsonResponse(RESPONSE_OK, None, {'result': res})
except Exception, e:
response = JsonResponse(RESPONSE_SERVERERROR)
return response
def __fillresponse(self, resp, searchtime, q=""):
finallist = list()
for res1 in resp.resultlistlist:
resourcetrie = res1.getTrie()
resourcetrie.prune()
res1dict = {
'resultlabel': res1.label,
'exactresult': res1.exactresult,
'nresults': len(res1.resultlist),
'resourcetrie': resourcetrie.dictify()
}
finallist.append(res1dict)
response = JsonResponse(RESPONSE_OK, None, {
'q': q,
'nresults': resp.getLen(),
'nlabels': len(resp.getLabels()),
'searchtime': searchtime,
'results': finallist
})
return response
def query(self, request):
try:
if not request.has_key('q'):
response = JsonResponse(RESPONSE_REQERROR, "Bad request: search term(s) missing")
return response
req = request['q']
if request.has_key('nresults'):
try:
nres = int(request['nresults'])
except Exception, e:
response = JsonResponse(RESPONSE_REQERROR, "Bad request [%s]" % str(e))
return response
else:
nres = 200 #FIXME
q = Query(req)
if request.has_key('ip'):
q.server = request['ip']
if request.has_key('filetype'):
q.filetype = request['filetype'].upper()
tsta = time.time()
resp = self.qm.query(q, nres)
tend = time.time()
searchtime = tend - tsta
response = self.__fillresponse(resp, searchtime, req)
except Exception, e:
response = JsonResponse(RESPONSE_SERVERERROR, "Error [%s]" % str(e))
return response
def exactquery(self, request):
try:
if not request.has_key('q'):
response = JsonResponse(RESPONSE_REQERROR, "Bad request: search term(s) missing")
return response
req = request['q']
q = Query(req)
if request.has_key('ip'):
q.server = request['ip']
if request.has_key('filetype'):
q.filetype = request['filetype'].upper()
tsta = time.time()
resp = self.qm.exactquery(q)
tend = time.time()
searchtime = tend - tsta
response = self.__fillresponse(resp, searchtime, req)
except Exception, e:
response = JsonResponse(RESPONSE_SERVERERROR, "Error [%s]" % str(e))
return response
def orquery(self, request):
try:
if not request.has_key('q'):
response = JsonResponse(RESPONSE_REQERROR, "Bad request: search term(s) missing")
return response
req = request['q']
q = Query(req)
if request.has_key('ip'):
q.server = request['ip']
if request.has_key('filetype'):
q.filetype = request['filetype'].upper()
tsta = time.time()
resp = self.qm.orquery(q)
tend = time.time()
searchtime = tend - tsta
response = self.__fillresponse(resp, searchtime, req)
except Exception, e:
response = JsonResponse(RESPONSE_SERVERERROR, "Error [%s]" % str(e))
return response
def likequery(self, request):
try:
if not request.has_key('q'):
response = JsonResponse(RESPONSE_REQERROR, "Bad request: search term(s) missing")
return response
req = request['q']
if request.has_key('words'):
try:
limit = int(request['words'])
except Exception, e:
response = JsonResponse(RESPONSE_REQERROR, "Bad request [%s]" % str(e))
return response
else:
limit = 3 #FIXME
q = Query(req)
if request.has_key('ip'):
q.server = request['ip']
if request.has_key('filetype'):
q.filetype = request['filetype'].upper()
tsta = time.time()
resp = self.qm.likequery(q, limit)
tend = time.time()
searchtime = tend - tsta
response = self.__fillresponse(resp, searchtime, req)
except Exception, e:
response = JsonResponse(RESPONSE_SERVERERROR, "Error [%s]" % str(e))
return response
def whatsnew(self, request):
try:
if request.has_key('nresults'):
try:
nres = int(request['nresults'])
except Exception, e:
response = JsonResponse(RESPONSE_REQERROR, "Bad request [%s]" % str(e))
return response
else:
nres = 200 #FIXME
tsta = time.time()
resp = self.qm.getNewFiles(nres)
tend = time.time()
searchtime = tend - tsta
response = self.__fillresponse(resp, searchtime, "")
except Exception, e:
response = JsonResponse(RESPONSE_SERVERERROR, "Error [%s]" % str(e))
return response
def serverlist(self, request):
"return the list of servers indexed by the search engine"
try:
res = self.qm.getServerList()
response = JsonResponse(RESPONSE_OK, None, {'result': res})
except Exception, e:
response = JsonResponse(RESPONSE_SERVERERROR, str(e))
return response