add comment on offline mode that is not usable anymore as such
[myslice.git] / manifold / manifoldproxy.py
1 import json
2 import os.path
3
4 # this is for django objects only
5 #from django.core import serializers
6 from django.http                import HttpResponse, HttpResponseForbidden
7
8 #from manifold.manifoldquery import ManifoldQuery
9 from manifold.core.query        import Query
10 from manifold.core.result_value import ResultValue
11 from manifold.manifoldapi       import ManifoldAPI
12 from manifold.manifoldresult    import ManifoldException
13 from manifold.util.log          import Log
14 from myslice.config             import Config
15
16 debug=False
17 debug=True
18
19 # add artificial delay in s
20 debug_spin=0
21 #debug_spin=1
22
23 # pretend the server only returns - empty lists to 'get' requests - this is to mimick 
24 # misconfigurations or expired credentials or similar corner case situations
25 debug_empty=False
26 #debug_empty=True
27
28 # Historically we had a feature for developing without an Internet connection
29 # However this won't work anymore as the python layer itself does manifold calls
30 # before javascript has a chance to do so.
31 # Might still come in handy if you want the fastest possible (locally cached) feedback
32 # beware that this is very rough though...
33 work_offline=False
34 #work_offline=True
35
36 # this view is what the javascript talks to when it sends a query
37 # see also
38 # myslice/urls.py
39 # as well as 
40 # static/js/manifold.js
41 def proxy (request,format):
42     """the view associated with /manifold/proxy/ 
43 with the query passed using POST"""
44     
45     # expecting a POST
46     if request.method != 'POST':
47         print "manifoldproxy.api: unexpected method %s -- exiting"%request.method
48         return 
49     # we only support json for now
50     # if needed in the future we should probably cater for
51     # format_in : how is the query encoded in POST
52     # format_out: how to serve the results
53     if format != 'json':
54         print "manifoldproxy.proxy: unexpected format %s -- exiting"%format
55         return
56     try:
57         # translate incoming POST request into a query object
58         if debug: print 'manifoldproxy.proxy: request.POST',request.POST
59         manifold_query = Query()
60         #manifold_query = ManifoldQuery()
61         manifold_query.fill_from_POST(request.POST)
62         offline_filename="%s/../offline-%s-%s.json"%(os.path.dirname(__file__),manifold_query.action,manifold_query.object)
63         # retrieve session for request
64
65         # We allow some requests to use the ADMIN user account
66         if (manifold_query.get_from() == 'local:user' and manifold_query.get_action() == 'create') \
67                 or (manifold_query.get_from() == 'local:platform' and manifold_query.get_action() == 'get'):
68             admin_user, admin_password = Config().manifold_admin_user_password()
69             manifold_api_session_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
70         else:
71             manifold_api_session_auth = request.session['manifold']['auth']
72
73         if debug_empty and manifold_query.action.lower()=='get':
74             json_answer=json.dumps({'code':0,'value':[]})
75             print "By-passing : debug_empty & 'get' request : returning a fake empty list"
76             return HttpResponse (json_answer, mimetype="application/json")
77         ### patch : return the latest one..
78         if work_offline:
79             # if that won't work then we'll try to update anyways
80             try:
81                 with (file(offline_filename,"r")) as f:
82                     json_answer=f.read()
83                 print "By-passing : using contents from %s"%offline_filename
84                 return HttpResponse (json_answer, mimetype="application/json")
85             except:
86                 import traceback
87                 traceback.print_exc()
88                 print "Could not run in offline mode, PROCEEDING"
89                 pass
90                 
91         # actually forward
92         manifold_api= ManifoldAPI(auth=manifold_api_session_auth)
93         if debug: print '===> manifoldproxy.proxy: sending to backend', manifold_query
94         # for the benefit of the python code, manifoldAPI raises an exception if something is wrong
95         # however in this case we want to propagate the complete manifold result to the js world
96
97         result = manifold_api.forward(manifold_query.to_dict())
98
99         # XXX TEMP HACK
100         if 'description' in result and result['description'] \
101                 and isinstance(result['description'], (tuple, list, set, frozenset)):
102             result [ 'description' ] = [ ResultValue.to_html (x) for x in result['description'] ]
103
104         json_answer=json.dumps(result)
105         # if in debug mode we save this so we can use offline mode later
106         if debug:
107             with (file(offline_filename,"w")) as f:
108                 f.write(json_answer)
109
110         # this is an artificial delay added for debugging purposes only
111         if debug_spin>0:
112             print "Adding additional artificial delay",debug_spin
113             import time
114             time.sleep(debug_spin)
115
116         return HttpResponse (json_answer, mimetype="application/json")
117
118     except Exception,e:
119         print "** PROXY ERROR **",e
120         import traceback
121         traceback.print_exc()
122
123 #################### 
124 # see CSRF_FAILURE_VIEW in settings.py
125 # the purpose of redefining this was to display the failure reason somehow
126 # this however turns out disappointing/not very informative
127 failure_answer=[ "csrf_failure" ]
128 def csrf_failure(request, reason=""):
129     print "CSRF failure with reason '%s'"%reason
130     return HttpResponseForbidden (json.dumps (failure_answer), mimetype="application/json")