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