updated plugins
[unfold.git] / manifold / js / manifold.js
1 // utilities 
2 function debug_dict_keys (msg, o) {
3     var keys=[];
4     for (var k in o) keys.push(k);
5     messages.debug ("debug_dict_keys: " + msg + " keys= " + keys);
6 }
7 function debug_dict (msg, o) {
8     for (var k in o) messages.debug ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
9 }
10 function debug_value (msg, value) {
11     messages.debug ("debug_value: " + msg + " " + value);
12 }
13 function debug_query (msg, query) {
14     if (query === undefined) messages.debug ("debug_query: " + msg + " -> undefined");
15     else if (query == null) messages.debug ("debug_query: " + msg + " -> null");
16     else if ('query_uuid' in query) messages.debug ("debug_query: " + msg + query.__repr());
17     else messages.debug ("debug_query: " + msg + " query= " + query);
18 }
19
20 /* ------------------------------------------------------------ */
21
22 /*!
23  * This namespace holds functions for globally managing query objects
24  * \Class Manifold
25  */
26 var manifold = {
27
28     spin_presets: {},
29
30     spin: function(locator, active /*= true */) {
31         active = typeof active !== 'undefined' ? active : true;
32         try {
33             if (active) {
34                 $(locator).spin(manifold.spin_presets);
35             } else {
36                 $locator.spin(false);
37             }
38         } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
39     },
40
41     /*!
42      * Associative array storing the set of queries active on the page
43      * \memberof Manifold
44      */
45     all_queries: {},
46
47     /*!
48      * Insert a query in the global hash table associating uuids to queries.
49      * If the query has no been analyzed yet, let's do it.
50      * \fn insert_query(query)
51      * \memberof Manifold
52      * \param ManifoldQuery query Query to be added
53      */
54     insert_query : function (query) { 
55         if (query.analyzed_query == null) {
56             query.analyze_subqueries();
57         }
58         manifold.all_queries[query.query_uuid]=query;
59     },
60
61     /*!
62      * Returns the query associated to a UUID
63      * \fn find_query(query_uuid)
64      * \memberof Manifold
65      * \param string query_uuid The UUID of the query to be returned
66      */
67     find_query : function (query_uuid) { 
68         return manifold.all_queries[query_uuid];
69     },
70
71     // trigger a query asynchroneously
72     proxy_url : '/manifold/proxy/json/',
73
74     asynchroneous_debug : true,
75
76     /**
77      * \brief We use js function closure to be able to pass the query (array)
78      * to the callback function used when data is received
79      */
80     success_closure: function(query, publish_uuid, domid)
81     {
82         return function(data, textStatus) {
83             manifold.asynchroneous_success(data, query, publish_uuid, domid);
84         }
85     },
86
87     // Executes all async. queries
88     // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
89     asynchroneous_exec : function (query_publish_dom_tuples) {
90         // start spinners
91
92         // in case the spin stuff was not loaded, let's make sure we proceed to the exit 
93         try {
94             if (manifold.asynchroneous_debug) 
95             messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
96             jQuery('.need-spin').spin(manifold.spin_presets);
97         } catch (err) { messages.debug("Cannot turn on spins " + err); }
98         
99         // Loop through input array, and use publish_uuid to publish back results
100         jQuery.each(query_publish_dom_tuples, function(index, tuple) {
101             var query=manifold.find_query(tuple.query_uuid);
102             var query_json=JSON.stringify (query);
103             var publish_uuid=tuple.publish_uuid;
104             // by default we publish using the same uuid of course
105             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
106             if (manifold.asynchroneous_debug) {
107                 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
108                 messages.debug("... ctd... with actual query= " + query.__repr());
109             }
110             // not quite sure what happens if we send a string directly, as POST data is named..
111             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
112                 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.domid));
113         })
114     },
115
116     /**
117      * \brief Forward a query to the manifold backend
118      * \param query (dict) the query to be executed asynchronously
119      * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
120      */
121     forward: function(query, domid) {
122         var query_json = JSON.stringify(query);
123         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, domid));
124     },
125
126     /*!
127      * Returns whether a query expects a unique results.
128      * This is the case when the filters contain a key of the object
129      * \fn query_expects_unique_result(query)
130      * \memberof Manifold
131      * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
132      */
133     query_expects_unique_result: function(query) {
134         /* XXX we need functions to query metadata */
135         //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
136         /* TODO requires keys in metadata */
137         return true;
138     },
139
140     /*!
141      * Publish result
142      * \fn publish_result(query, results)
143      * \memberof Manifold
144      * \param ManifoldQuery query Query which has received results
145      * \param array results results corresponding to query
146      */
147     publish_result: function(query, result) {
148         /* Publish an update announce */
149         var channel="/results/" + query.query_uuid + "/changed";
150         if (manifold.asynchroneous_debug) messages.debug("publishing result on " + channel);
151         jQuery.publish(channel, [result, query]);
152     },
153
154     /*!
155      * Recursively publish result
156      * \fn publish_result_rec(query, result)
157      * \memberof Manifold
158      * \param ManifoldQuery query Query which has received result
159      * \param array result result corresponding to query
160      */
161     publish_result_rec: function(query, result) {
162         /* If the result is not unique, only publish the top query;
163          * otherwise, publish the main object as well as subqueries
164          * XXX how much recursive are we ?
165          */
166         if (manifold.query_expects_unique_result(query)) {
167             /* Also publish subqueries */
168             jQuery.each(query.subqueries, function(object, subquery) {
169                 manifold.publish_result_rec(subquery, result[0][object]);
170                 /* TODO remove object from result */
171             });
172         }
173         manifold.publish_result(query, result);
174     },
175
176     // if set domid allows the result to be directed to just one plugin
177     // most of the time publish_uuid will be query.query_uuid
178     // however in some cases we wish to publish the result under a different uuid
179     // e.g. an updater wants to publish its result as if from the original (get) query
180     asynchroneous_success : function (data, query, publish_uuid, domid) {
181         // xxx should have a nicer declaration of that enum in sync with the python code somehow
182         if (data.code == 2) { // ERROR
183             alert("Your session has expired, please log in again");
184             window.location="/logout/";
185             return;
186         }
187         if (data.code == 1) { // WARNING
188             messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
189             // publish error code and text message on a separate channel for whoever is interested
190             jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
191         }
192         // once everything is checked we can use the 'value' part of the manifoldresult
193         var result=data.value;
194         if (result) {
195             if (!!domid) {
196                 /* Directly inform the requestor */
197                 if (manifold.asynchroneous_debug) messages.debug("directing result to " + domid);
198                 jQuery('#' + domid).trigger('results', [result]);
199             } else {
200                 /* XXX Jordan XXX I don't need publish_uuid here... What is it used for ? */
201                 /* query is the query we sent to the backend; we need to find the
202                  * corresponding analyezd_query in manifold.all_queries
203                  */
204                 tmp_query = manifold.find_query(query.query_uuid);
205                 manifold.publish_result_rec(tmp_query.analyzed_query, result);
206             }
207
208         }
209     },
210
211 }; // manifold object
212 /* ------------------------------------------------------------ */
213
214 // extend jQuery/$ with pubsub capabilities
215 /* https://gist.github.com/661855 */
216 (function($) {
217
218   var o = $({});
219
220   $.subscribe = function( channel, selector, data, fn) {
221     /* borrowed from jQuery */
222     if ( data == null && fn == null ) {
223         // ( channel, fn )
224         fn = selector;
225         data = selector = undefined;
226     } else if ( fn == null ) {
227         if ( typeof selector === "string" ) {
228             // ( channel, selector, fn )
229             fn = data;
230             data = undefined;
231         } else {
232             // ( channel, data, fn )
233             fn = data;
234             data = selector;
235             selector = undefined;
236         }
237     }
238     /* </ugly> */
239
240     /* We use an indirection function that will clone the object passed in
241      * parameter to the subscribe callback 
242      * 
243      * FIXME currently we only clone query objects which are the only ones
244      * supported and editable, we might have the same issue with results but
245      * the page load time will be severely affected...
246      */
247     o.on.apply(o, [channel, selector, data, function() { 
248         for(i = 1; i < arguments.length; i++) {
249             if ( arguments[i].constructor.name == 'ManifoldQuery' )
250                 arguments[i] = arguments[i].clone();
251         }
252         fn.apply(o, arguments);
253     }]);
254   };
255
256   $.unsubscribe = function() {
257     o.off.apply(o, arguments);
258   };
259
260   $.publish = function() {
261     o.trigger.apply(o, arguments);
262   };
263
264 }(jQuery));
265
266 /* ------------------------------------------------------------ */
267
268 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
269 //make sure to expose csrf in our outcoming ajax/post requests
270 $.ajaxSetup({ 
271      beforeSend: function(xhr, settings) {
272          function getCookie(name) {
273              var cookieValue = null;
274              if (document.cookie && document.cookie != '') {
275                  var cookies = document.cookie.split(';');
276                  for (var i = 0; i < cookies.length; i++) {
277                      var cookie = jQuery.trim(cookies[i]);
278                      // Does this cookie string begin with the name we want?
279                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
280                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
281                      break;
282                  }
283              }
284          }
285          return cookieValue;
286          }
287          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
288              // Only send the token to relative URLs i.e. locally.
289              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
290          }
291      } 
292 });
293