89c83d1748933056c4966a207d121d520c725cfe
[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 /* Update requests from plugins */
36 var SET_ADD        = 201;
37 var SET_REMOVED    = 202;
38
39 /* Query status */
40 var STATUS_NONE               = 500; // Query has not been started yet
41 var STATUS_GET_IN_PROGRESS    = 501; // Query has been sent, no result has been received
42 var STATUS_GET_RECEIVED       = 502; // Success
43 var STATUS_GET_ERROR          = 503; // Error
44 var STATUS_UPDATE_PENDING     = 504;
45 var STATUS_UPDATE_IN_PROGRESS = 505;
46 var STATUS_UPDATE_RECEIVED    = 506;
47 var STATUS_UPDATE_ERROR       = 507;
48 // outdated ?
49
50 // A structure for storing queries
51
52
53
54 function QueryExt(query, parent_query, main_query) {
55
56     /* Constructor */
57     if (typeof query == "undefined")
58         throw "Must pass a query in QueryExt constructor";
59     this.query        = query
60     this.parent_query = (typeof parent_query == "undefined") ? false : parent_query
61     this.main_query   = (typeof main_query   == "undefined") ? false : main_query
62     
63     this.status       = null;
64     this.results      = null;
65     this.update_query = null; // null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
66 }
67
68 function QueryStore() {
69
70     this.main_queries     = {};
71     this.analyzed_queries = {};
72
73     /* Insertion */
74
75     this.insert = function(query)
76     {
77         if (query.analyzed_query == null) {
78             query.analyze_subqueries();
79         }
80
81         query_ext = new QueryExt(query, null, null)
82         manifold.query_store.main_queries[query.query_uuid] = query_ext;
83
84         // We also need to insert all queries and subqueries from the analyzed_query
85         query.iter_subqueries(function(sq, data, parent_query) {
86             if (parent_query)
87                 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
88             else
89                 parent_query_ext = null;
90             sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
91             manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
92         });
93     }
94
95     /* Searching */
96
97     this.find_query_ext = function(query_uuid)
98     {
99         return this.main_queries[query_uuid];
100     }
101
102     this.find_query = function(query_uuid)
103     {
104         return this.find_query_ext(query_uuid).query;
105     }
106
107     this.find_analyzed_query_ext = function(query_uuid)
108     {
109         return this.analyzed_queries[query_uuid];
110     }
111
112     this.find_analyzed_query = function(query_uuid)
113     {
114         return this.find_analyzed_query_ext(query_uuid).query;
115     }
116 }
117
118 /*!
119  * This namespace holds functions for globally managing query objects
120  * \Class Manifold
121  */
122 var manifold = {
123
124     /************************************************************************** 
125      * Helper functions
126      **************************************************************************/ 
127
128     spin_presets: {},
129
130     spin: function(locator, active /*= true */) {
131         active = typeof active !== 'undefined' ? active : true;
132         try {
133             if (active) {
134                 $(locator).spin(manifold.spin_presets);
135             } else {
136                 $(locator).spin(false);
137             }
138         } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
139     },
140
141     /************************************************************************** 
142      * Query management
143      **************************************************************************/ 
144
145     query_store: new QueryStore(),
146
147     // XXX Remaining functions are deprecated since they are replaced by the query store
148
149     /*!
150      * Associative array storing the set of queries active on the page
151      * \memberof Manifold
152      */
153     all_queries: {},
154
155     /*!
156      * Insert a query in the global hash table associating uuids to queries.
157      * If the query has no been analyzed yet, let's do it.
158      * \fn insert_query(query)
159      * \memberof Manifold
160      * \param ManifoldQuery query Query to be added
161      */
162     insert_query : function (query) { 
163         // NEW API
164         manifold.query_store.insert(query);
165
166         // FORMER API
167         if (query.analyzed_query == null) {
168             query.analyze_subqueries();
169         }
170         manifold.all_queries[query.query_uuid]=query;
171     },
172
173     /*!
174      * Returns the query associated to a UUID
175      * \fn find_query(query_uuid)
176      * \memberof Manifold
177      * \param string query_uuid The UUID of the query to be returned
178      */
179     find_query : function (query_uuid) { 
180         return manifold.all_queries[query_uuid];
181     },
182
183     /************************************************************************** 
184      * Query execution
185      **************************************************************************/ 
186
187     // trigger a query asynchroneously
188     proxy_url : '/manifold/proxy/json/',
189
190     asynchroneous_debug : true,
191
192     /**
193      * \brief We use js function closure to be able to pass the query (array)
194      * to the callback function used when data is received
195      */
196     success_closure: function(query, publish_uuid, callback /*domid*/)
197     {
198         return function(data, textStatus) {
199             manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
200         }
201     },
202
203     // Executes all async. queries
204     // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
205     asynchroneous_exec : function (query_publish_dom_tuples) {
206         // start spinners
207
208         // in case the spin stuff was not loaded, let's make sure we proceed to the exit 
209         //try {
210         //    if (manifold.asynchroneous_debug) 
211         //   messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
212         //    jQuery('.need-spin').spin(manifold.spin_presets);
213         //} catch (err) { messages.debug("Cannot turn on spins " + err); }
214         
215         // Loop through input array, and use publish_uuid to publish back results
216         jQuery.each(query_publish_dom_tuples, function(index, tuple) {
217             var query=manifold.find_query(tuple.query_uuid);
218             var query_json=JSON.stringify (query);
219             var publish_uuid=tuple.publish_uuid;
220             // by default we publish using the same uuid of course
221             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
222             if (manifold.asynchroneous_debug) {
223                 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
224                 messages.debug("... ctd... with actual query= " + query.__repr());
225             }
226
227             query.iter_subqueries(function (sq) {
228                 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
229             });
230
231             // not quite sure what happens if we send a string directly, as POST data is named..
232             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
233                 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
234         })
235     },
236
237     /**
238      * \brief Forward a query to the manifold backend
239      * \param query (dict) the query to be executed asynchronously
240      * \param callback (function) the function to be called when the query terminates
241      * Deprecated:
242      * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
243      */
244     forward: function(query, callback /*domid*/) {
245         var query_json = JSON.stringify(query);
246         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
247     },
248
249     /*!
250      * Returns whether a query expects a unique results.
251      * This is the case when the filters contain a key of the object
252      * \fn query_expects_unique_result(query)
253      * \memberof Manifold
254      * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
255      */
256     query_expects_unique_result: function(query) {
257         /* XXX we need functions to query metadata */
258         //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
259         /* TODO requires keys in metadata */
260         return true;
261     },
262
263     /*!
264      * Publish result
265      * \fn publish_result(query, results)
266      * \memberof Manifold
267      * \param ManifoldQuery query Query which has received results
268      * \param array results results corresponding to query
269      */
270     publish_result: function(query, result) {
271         if (typeof result === 'undefined')
272             result = [];
273
274         // NEW PLUGIN API
275         manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
276         $.each(result, function(i, record) {
277             manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
278         });
279         manifold.raise_record_event(query.query_uuid, DONE);
280
281         // OLD PLUGIN API BELOW
282         /* Publish an update announce */
283         var channel="/results/" + query.query_uuid + "/changed";
284         if (manifold.asynchroneous_debug)
285             messages.debug("publishing result on " + channel);
286         jQuery.publish(channel, [result, query]);
287     },
288
289     /*!
290      * Recursively publish result
291      * \fn publish_result_rec(query, result)
292      * \memberof Manifold
293      * \param ManifoldQuery query Query which has received result
294      * \param array result result corresponding to query
295      */
296     publish_result_rec: function(query, result) {
297         /* If the result is not unique, only publish the top query;
298          * otherwise, publish the main object as well as subqueries
299          * XXX how much recursive are we ?
300          */
301         if (manifold.query_expects_unique_result(query)) {
302             /* Also publish subqueries */
303             jQuery.each(query.subqueries, function(object, subquery) {
304                 manifold.publish_result_rec(subquery, result[0][object]);
305                 /* TODO remove object from result */
306             });
307         }
308         manifold.publish_result(query, result);
309     },
310
311     // if set domid allows the result to be directed to just one plugin
312     // most of the time publish_uuid will be query.query_uuid
313     // however in some cases we wish to publish the result under a different uuid
314     // e.g. an updater wants to publish its result as if from the original (get) query
315     asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
316         // xxx should have a nicer declaration of that enum in sync with the python code somehow
317
318         /* If a callback has been specified, we redirect results to it */
319         if (!!callback) { callback(data); return; }
320
321         if (data.code == 2) { // ERROR
322             // We need to make sense of error codes here
323             alert("Your session has expired, please log in again");
324             window.location="/logout/";
325             return;
326         }
327         if (data.code == 1) { // WARNING
328             messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
329             // publish error code and text message on a separate channel for whoever is interested
330             jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
331
332             $("#notifications").notify("create", "sticky", {
333               title: 'Warning',
334               text: data.description
335             },{
336               expires: false,
337               speed: 1000
338             });
339             
340         }
341         // once everything is checked we can use the 'value' part of the manifoldresult
342         var result=data.value;
343         if (result) {
344             //if (!!callback /* domid */) {
345             //    /* Directly inform the requestor */
346             //    if (manifold.asynchroneous_debug) messages.debug("directing result to callback");
347             //    callback(result);
348             //    //if (manifold.asynchroneous_debug) messages.debug("directing result to " + domid);
349             //    //jQuery('#' + domid).trigger('results', [result]);
350             //} else {
351                 /* XXX Jordan XXX I don't need publish_uuid here... What is it used for ? */
352                 /* query is the query we sent to the backend; we need to find the
353                  * corresponding analyezd_query in manifold.all_queries
354                  */
355                 tmp_query = manifold.find_query(query.query_uuid);
356                 manifold.publish_result_rec(tmp_query.analyzed_query, result);
357             //}
358
359         }
360     },
361
362     /************************************************************************** 
363      * Plugin API helpers
364      **************************************************************************/ 
365
366     raise_event_handler: function(type, query_uuid, event_type, value)
367     {
368         if (type == 'query') {
369             var channels = [ manifold.get_query_channel(query_uuid), manifold.get_query_channel('*') ];
370         } else if (type == 'record') {
371             var channels = [ manifold.get_record_channel(query_uuid), manifold.get_record_channel('*') ];
372
373         } else {
374             throw 'Incorrect type for manifold.raise_event()';
375         }
376         $.each(channels, function(i, channel) {
377             if (value === undefined)
378                 $('.plugin').trigger(channel, [event_type]);
379             else
380                 $('.plugin').trigger(channel, [event_type, value]);
381         });
382     },
383
384     raise_query_event: function(query_uuid, event_type, value)
385     {
386         manifold.raise_event_handler('query', query_uuid, event_type, value);
387     },
388
389     raise_record_event: function(query_uuid, event_type, value)
390     {
391         manifold.raise_event_handler('record', query_uuid, event_type, value);
392     },
393
394
395     raise_event: function(query_uuid, event_type, value)
396     {
397         switch(event_type) {
398             case SET_ADD:
399                 // Query uuid has been updated with the key of a new element
400                 query_ext    = manifold.query_store.find_analyzed_query(query_uuid);
401
402                 // update is only possible is the query is not pending, etc
403                 // CHECK status !
404
405                 // XXX we can only update subqueries of the main query. Check !
406                 // assert query_ext.parent_query == query_ext.main_query
407                 update_query = query_ext.parent_query.update_query;
408
409                 // NOTE: update might modify the fields in Get
410                 // NOTE : we have to modify all child queries
411                 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
412
413                 // if everything is done right, update_query should not be null. It is updated when we received results from the get query
414                 // object = the same as get
415                 // filter = key : update a single object for now
416                 // fields = the same as get
417
418                 break;
419             case SET_REMOVED:
420                 // Query uuid has been updated with the key of a removed element
421                 break;
422         }
423     },
424
425     /* Publish/subscribe channels for internal use */
426     get_query_channel:  function(uuid) { return '/query/'  + uuid },
427     get_record_channel: function(uuid) { return '/record/' + uuid },
428
429 }; // manifold object
430 /* ------------------------------------------------------------ */
431
432 (function($) {
433
434     /* NEW PLUGIN API
435      * 
436      * NOTE: Since we don't have a plugin class, we are extending all jQuery
437      * plugins...
438      */
439
440     /*!
441      * \brief Associates a query handler to the current plugin
442      * \param uuid (string) query uuid
443      * \param handler (function) handler callback
444      */
445     $.fn.set_query_handler = function(uuid, handler)
446     {
447         this.on(manifold.get_query_channel(uuid), handler);
448     }
449
450     $.fn.set_record_handler = function(uuid, handler)
451     {
452         this.on(manifold.get_record_channel(uuid), handler);
453     }
454
455     // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
456     // https://gist.github.com/661855
457     var o = $({});
458     $.subscribe = function( channel, selector, data, fn) {
459       /* borrowed from jQuery */
460       if ( data == null && fn == null ) {
461           // ( channel, fn )
462           fn = selector;
463           data = selector = undefined;
464       } else if ( fn == null ) {
465           if ( typeof selector === "string" ) {
466               // ( channel, selector, fn )
467               fn = data;
468               data = undefined;
469           } else {
470               // ( channel, data, fn )
471               fn = data;
472               data = selector;
473               selector = undefined;
474           }
475       }
476       /* </ugly> */
477   
478       /* We use an indirection function that will clone the object passed in
479        * parameter to the subscribe callback 
480        * 
481        * FIXME currently we only clone query objects which are the only ones
482        * supported and editable, we might have the same issue with results but
483        * the page load time will be severely affected...
484        */
485       o.on.apply(o, [channel, selector, data, function() { 
486           for(i = 1; i < arguments.length; i++) {
487               if ( arguments[i].constructor.name == 'ManifoldQuery' )
488                   arguments[i] = arguments[i].clone();
489           }
490           fn.apply(o, arguments);
491       }]);
492     };
493   
494     $.unsubscribe = function() {
495       o.off.apply(o, arguments);
496     };
497   
498     $.publish = function() {
499       o.trigger.apply(o, arguments);
500     };
501   
502 }(jQuery));
503
504 /* ------------------------------------------------------------ */
505
506 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
507 //make sure to expose csrf in our outcoming ajax/post requests
508 $.ajaxSetup({ 
509      beforeSend: function(xhr, settings) {
510          function getCookie(name) {
511              var cookieValue = null;
512              if (document.cookie && document.cookie != '') {
513                  var cookies = document.cookie.split(';');
514                  for (var i = 0; i < cookies.length; i++) {
515                      var cookie = jQuery.trim(cookies[i]);
516                      // Does this cookie string begin with the name we want?
517                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
518                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
519                      break;
520                  }
521              }
522          }
523          return cookieValue;
524          }
525          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
526              // Only send the token to relative URLs i.e. locally.
527              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
528          }
529      } 
530 });
531