use logger instead of print as often as possible
[myslice.git] / unfold / page.py
1 # the supervisor for Plugins
2 # keeps a handle on all present plugins for managing their queries in a consistent way
3 # it is expected to exist one such object for a given page
4
5 import json
6
7 from django.template.loader import render_to_string
8
9 from manifoldapi.metadata import MetaData
10
11 from unfold.prelude import Prelude
12
13 from myslice.configengine import ConfigEngine
14 from myslice.settings import logger
15
16 # decorator to deflect calls on this Page to its prelude
17 def to_prelude (method):
18     def actual (self, *args, **kwds):
19         prelude_method=Prelude.__dict__[method.__name__]
20         return prelude_method(self.prelude,*args, **kwds)
21     return actual
22
23 debug=False
24 debug=True
25
26 class Page:
27
28     def __init__ (self, request):
29         self.request=request
30         # all plugins mentioned in this page
31         self._plugins = {}
32         # the set of all queries 
33         self._queries=set()
34         # queue of queries with maybe a domid, see enqueue_query
35         self._queue=[]
36         # global prelude object
37         # global requirements should go in base.html
38         self.prelude=Prelude()
39
40     # record known plugins hashed on their domid
41     def record_plugin (self, plugin):
42         self._plugins[plugin.domid]=plugin
43
44     def get_plugin (self, domid):
45         return self._plugins.get(domid,None)
46
47     # not sure this is useful at all
48 #    def reset_queue (self):
49 #        self._queries = set()
50 #        self._queue = []
51
52     # this method adds a query to the page
53     # the query will be exposed to js when calling __expose_queries, which is done by prelude_env() 
54     # additionally if run_it is set to True, this query will be asynchroneously triggered on page load
55     # in this case (exec=True) the js async callback (see manifold.asynchroneous_success)
56     # offers the option to deliver the result to a specific DOM elt (in this case, set domid)
57     # otherwise (i.e. if domid not provided), it goes through the pubsub system (so all plugins can receive it)
58     # 
59     # NOTE:
60     # analyzed_query is required because it contains query_uuid that the
61     # plugins initialized in the python part will listen to. When a result is
62     # received in javascript, subresults should be publish to the appropriate
63     # query_uuid.
64     # 
65     def enqueue_query (self, query, run_it=True, domid=None, analyzed_query=None):
66         # _queries is the set of all known queries
67         # XXX complex XXX self._queries = self._queries.union(set( [ query, ] ))
68         self._queries.add((query, analyzed_query))
69         # _queue is the list of queries that need to be triggered, with an optional domid
70         # we only do this if run_it is set
71         if run_it: self._queue.append ( (query.query_uuid,domid) )
72
73     def generate_records(self, query, generators, number=10):
74         self.add_js_files('js/record_generator.js');
75         js_chunk = '$(document).ready(function() { new RecordGenerator(%s,%s,%s).run(); });'%(query.to_json(),json.dumps(generators),number);
76         self.add_js_chunks(js_chunk)
77     
78     # return the javascript code for exposing queries
79     # all queries are inserted in the global manifold object
80     # in addition, the ones enqueued with 'run_it=True' are triggered 
81     def __expose_queries (self):
82         # compute variables to expose to the template
83         env = {}
84         # expose the json definition of all queries
85         env['queries_json'] = [ query.to_json(analyzed_query=aq) for (query, aq) in self._queries ]
86         def query_publish_dom_tuple (a,b):
87             result={'query_uuid':a}
88             if b: result['domid']=b
89             return result
90         env['query_exec_tuples'] = [ query_publish_dom_tuple (a,b) for (a,b) in self._queue ]
91         javascript = render_to_string ("page-queries.js",env)
92         self.add_js_chunks (javascript)
93 #        self.reset_queue()
94         # unconditionnally expose MANIFOLD_URL, this is small and manifold.js uses that for various messages
95         self.expose_js_manifold_config()
96
97
98     # needs to be called explicitly and only when metadata is actually required
99     # in particular user needs to be logged
100     def get_metadata (self):
101         # look in session's cache - we don't want to retrieve this for every request
102         session=self.request.session
103
104         if 'manifold' not in session:
105             session['manifold'] = {}
106         manifold = session['manifold']
107
108         # if cached, use it
109         if 'metadata' in manifold and isinstance(manifold['metadata'],MetaData):
110             logger.debug("Page.get_metadata: return cached value")
111             return manifold['metadata']
112
113         metadata_auth = {'AuthMethod':'anonymous'}
114
115         metadata=MetaData (metadata_auth)
116         metadata.fetch(self.request)
117         # store it for next time
118         manifold['metadata']=metadata
119         logger.debug("Page.get_metadata: return new value")
120         return metadata
121             
122     def expose_js_metadata (self):
123         # expose global MANIFOLD_METADATA as a js variable
124         # xxx this is fetched synchroneously..
125         self.add_js_init_chunks("var MANIFOLD_METADATA =" + self.get_metadata().to_json() + ";\n")
126
127     def expose_js_var(self, name, value):
128         # expose variable as a js value
129         self.add_js_init_chunks("var " + name + "=" + value + ";\n")
130
131     def expose_js_manifold_config (self):
132         self.add_js_init_chunks(ConfigEngine().manifold_js_export())
133
134     #################### requirements/prelude management
135     # just forward to self.prelude - see decorator above
136     @to_prelude
137     def add_js_files (self):pass
138     @to_prelude
139     def add_css_files (self):pass
140     @to_prelude
141     def add_js_init_chunks (self):pass
142     @to_prelude
143     def add_js_chunks (self):pass
144     @to_prelude
145     def add_css_chunks (self):pass
146
147     # prelude_env also does expose_queries
148     def prelude_env (self):
149         self.__expose_queries()
150         from_prelude=self.prelude.prelude_env()
151         return from_prelude