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