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