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