abbd6e6d6b1b06d6d79d5fb91d3c0f39179f1280
[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 var RUN_UPDATE     = 203;
39
40 /* Query status */
41 var STATUS_NONE               = 500; // Query has not been started yet
42 var STATUS_GET_IN_PROGRESS    = 501; // Query has been sent, no result has been received
43 var STATUS_GET_RECEIVED       = 502; // Success
44 var STATUS_GET_ERROR          = 503; // Error
45 var STATUS_UPDATE_PENDING     = 504;
46 var STATUS_UPDATE_IN_PROGRESS = 505;
47 var STATUS_UPDATE_RECEIVED    = 506;
48 var STATUS_UPDATE_ERROR       = 507;
49 // outdated ?
50
51 // A structure for storing queries
52
53
54
55 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled) {
56
57     /* Constructor */
58     if (typeof query == "undefined")
59         throw "Must pass a query in QueryExt constructor";
60     this.query            = query
61     this.parent_query_ext = (typeof parent_query_ext == "undefined") ? null : parent_query_ext
62     this.main_query_ext   = (typeof main_query_ext   == "undefined") ? null : main_query_ext
63     this.update_query_ext = (typeof update_query_ext   == "undefined") ? null : update_query_ext
64     this.disabled         = (typeof update_query_ext   == "undefined") ? false : disabled
65     
66     this.status       = null;
67     this.results      = null;
68     // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
69 }
70
71 function QueryStore() {
72
73     this.main_queries     = {};
74     this.analyzed_queries = {};
75
76     /* Insertion */
77
78     this.insert = function(query)
79     {
80         // We expect only main_queries are inserted
81
82         /* If the query has not been analyzed, then we analyze it */
83         if (query.analyzed_query == null) {
84             query.analyze_subqueries();
85         }
86
87         /* We prepare the update query corresponding to the main query and store both */
88         /* Note: they have the same UUID */
89
90         // XXX query.change_action() should become deprecated
91         update_query = query.clone();
92         update_query.action = 'update';
93         update_query.analyzed_query.action = 'update';
94         update_query.params = {};
95         update_query_ext = new QueryExt(update_query);
96         console.log("Update query created from Get query", update_query);
97
98         /* We store the main query */
99         query_ext = new QueryExt(query, null, null, update_query_ext, false);
100         manifold.query_store.main_queries[query.query_uuid] = query_ext;
101         /* Note: the update query does not have an entry! */
102
103
104         // The query is disabled; since it is incomplete until we know the content of the set of subqueries
105         // XXX unless we have no subqueries ???
106         // we will complete with params when records are received... this has to be done by the manager
107         // SET_ADD, SET_REMOVE will change the status of the elements of the set
108         // UPDATE will change also, etc.
109         // XXX We need a proper structure to store this information...
110
111         // We also need to insert all queries and subqueries from the analyzed_query
112         // XXX We need the root of all subqueries
113         query.iter_subqueries(function(sq, data, parent_query) {
114             if (parent_query)
115                 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
116             else
117                 parent_query_ext = null;
118             // XXX parent_query_ext == false
119             // XXX main.subqueries = {} # Normal, we need analyzed_query
120             sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
121             manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
122         });
123
124         // XXX We have spurious update queries...
125     }
126
127     /* Searching */
128
129     this.find_query_ext = function(query_uuid)
130     {
131         return this.main_queries[query_uuid];
132     }
133
134     this.find_query = function(query_uuid)
135     {
136         return this.find_query_ext(query_uuid).query;
137     }
138
139     this.find_analyzed_query_ext = function(query_uuid)
140     {
141         return this.analyzed_queries[query_uuid];
142     }
143
144     this.find_analyzed_query = function(query_uuid)
145     {
146         return this.find_analyzed_query_ext(query_uuid).query;
147     }
148 }
149
150 /*!
151  * This namespace holds functions for globally managing query objects
152  * \Class Manifold
153  */
154 var manifold = {
155
156     /************************************************************************** 
157      * Helper functions
158      **************************************************************************/ 
159
160     separator: '__',
161
162     spin_presets: {},
163
164     spin: function(locator, active /*= true */) {
165         active = typeof active !== 'undefined' ? active : true;
166         try {
167             if (active) {
168                 $(locator).spin(manifold.spin_presets);
169             } else {
170                 $(locator).spin(false);
171             }
172         } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
173     },
174
175     /************************************************************************** 
176      * Metadata management
177      **************************************************************************/ 
178
179      metadata: {
180
181         get_table: function(method)
182         {
183             var table = MANIFOLD_METADATA[method];
184             return (typeof table === 'undefined') ? null : table;
185         },
186
187         get_columns: function(method)
188         {
189             var table = this.get_table(method);
190             if (!table) {
191                 return null;
192             }
193
194             return (typeof table.column === 'undefined') ? null : table.column;
195         },
196
197         get_key: function(method)
198         {
199             var table = this.get_table(method);
200             if (!table)
201                 return null;
202
203             return (typeof table.key === 'undefined') ? null : table.key;
204         },
205
206
207         get_column: function(method, name)
208         {
209             var columns = this.get_columns(method);
210             if (!columns)
211                 return null;
212
213             $.each(columns, function(i, c) {
214                 if (c.name == name)
215                     return c
216             });
217             return null;
218         },
219
220         get_type: function(method, name)
221         {
222             var table = this.get_table(method);
223             if (!table)
224                 return null;
225
226             return (typeof table.type === 'undefined') ? null : table.type;
227         }
228
229      },
230
231     /************************************************************************** 
232      * Query management
233      **************************************************************************/ 
234
235     query_store: new QueryStore(),
236
237     // XXX Remaining functions are deprecated since they are replaced by the query store
238
239     /*!
240      * Associative array storing the set of queries active on the page
241      * \memberof Manifold
242      */
243     all_queries: {},
244
245     /*!
246      * Insert a query in the global hash table associating uuids to queries.
247      * If the query has no been analyzed yet, let's do it.
248      * \fn insert_query(query)
249      * \memberof Manifold
250      * \param ManifoldQuery query Query to be added
251      */
252     insert_query : function (query) { 
253         // NEW API
254         manifold.query_store.insert(query);
255
256         // FORMER API
257         if (query.analyzed_query == null) {
258             query.analyze_subqueries();
259         }
260         manifold.all_queries[query.query_uuid]=query;
261     },
262
263     /*!
264      * Returns the query associated to a UUID
265      * \fn find_query(query_uuid)
266      * \memberof Manifold
267      * \param string query_uuid The UUID of the query to be returned
268      */
269     find_query : function (query_uuid) { 
270         return manifold.all_queries[query_uuid];
271     },
272
273     /************************************************************************** 
274      * Query execution
275      **************************************************************************/ 
276
277     // trigger a query asynchroneously
278     proxy_url : '/manifold/proxy/json/',
279
280     asynchroneous_debug : true,
281
282     /**
283      * \brief We use js function closure to be able to pass the query (array)
284      * to the callback function used when data is received
285      */
286     success_closure: function(query, publish_uuid, callback /*domid*/)
287     {
288         return function(data, textStatus) {
289             manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
290         }
291     },
292
293     // Executes all async. queries
294     // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
295     asynchroneous_exec : function (query_publish_dom_tuples) {
296         // start spinners
297
298         // in case the spin stuff was not loaded, let's make sure we proceed to the exit 
299         //try {
300         //    if (manifold.asynchroneous_debug) 
301         //   messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
302         //    jQuery('.need-spin').spin(manifold.spin_presets);
303         //} catch (err) { messages.debug("Cannot turn on spins " + err); }
304         
305         // Loop through input array, and use publish_uuid to publish back results
306         jQuery.each(query_publish_dom_tuples, function(index, tuple) {
307             var query=manifold.find_query(tuple.query_uuid);
308             var query_json=JSON.stringify (query);
309             var publish_uuid=tuple.publish_uuid;
310             // by default we publish using the same uuid of course
311             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
312             if (manifold.asynchroneous_debug) {
313                 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
314                 messages.debug("... ctd... with actual query= " + query.__repr());
315             }
316
317             query.iter_subqueries(function (sq) {
318                 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
319             });
320
321             // not quite sure what happens if we send a string directly, as POST data is named..
322             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
323                 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
324         })
325     },
326
327     /**
328      * \brief Forward a query to the manifold backend
329      * \param query (dict) the query to be executed asynchronously
330      * \param callback (function) the function to be called when the query terminates
331      * Deprecated:
332      * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
333      */
334     forward: function(query, callback /*domid*/) {
335         var query_json = JSON.stringify(query);
336         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
337     },
338
339     /*!
340      * Returns whether a query expects a unique results.
341      * This is the case when the filters contain a key of the object
342      * \fn query_expects_unique_result(query)
343      * \memberof Manifold
344      * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
345      */
346     query_expects_unique_result: function(query) {
347         /* XXX we need functions to query metadata */
348         //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
349         /* TODO requires keys in metadata */
350         return true;
351     },
352
353     /*!
354      * Publish result
355      * \fn publish_result(query, results)
356      * \memberof Manifold
357      * \param ManifoldQuery query Query which has received results
358      * \param array results results corresponding to query
359      */
360     publish_result: function(query, result) {
361         if (typeof result === 'undefined')
362             result = [];
363
364         // NEW PLUGIN API
365         manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
366         $.each(result, function(i, record) {
367             manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
368         });
369         manifold.raise_record_event(query.query_uuid, DONE);
370
371         // OLD PLUGIN API BELOW
372         /* Publish an update announce */
373         var channel="/results/" + query.query_uuid + "/changed";
374         if (manifold.asynchroneous_debug)
375             messages.debug("publishing result on " + channel);
376         jQuery.publish(channel, [result, query]);
377     },
378
379     /*!
380      * Recursively publish result
381      * \fn publish_result_rec(query, result)
382      * \memberof Manifold
383      * \param ManifoldQuery query Query which has received result
384      * \param array result result corresponding to query
385      */
386     publish_result_rec: function(query, result) {
387         /* If the result is not unique, only publish the top query;
388          * otherwise, publish the main object as well as subqueries
389          * XXX how much recursive are we ?
390          */
391         if (manifold.query_expects_unique_result(query)) {
392             /* Also publish subqueries */
393             jQuery.each(query.subqueries, function(object, subquery) {
394                 manifold.publish_result_rec(subquery, result[0][object]);
395                 /* TODO remove object from result */
396             });
397         }
398         manifold.publish_result(query, result);
399     },
400
401     // if set domid allows the result to be directed to just one plugin
402     // most of the time publish_uuid will be query.query_uuid
403     // however in some cases we wish to publish the result under a different uuid
404     // e.g. an updater wants to publish its result as if from the original (get) query
405     asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
406         // xxx should have a nicer declaration of that enum in sync with the python code somehow
407
408         /* If a callback has been specified, we redirect results to it */
409         if (!!callback) { callback(data); return; }
410
411         if (data.code == 2) { // ERROR
412             // We need to make sense of error codes here
413             alert("Your session has expired, please log in again");
414             window.location="/logout/";
415             return;
416         }
417         if (data.code == 1) { // WARNING
418             messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
419             // publish error code and text message on a separate channel for whoever is interested
420             jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
421
422             $("#notifications").notify("create", "sticky", {
423               title: 'Warning',
424               text: data.description
425             },{
426               expires: false,
427               speed: 1000
428             });
429             
430         }
431         // once everything is checked we can use the 'value' part of the manifoldresult
432         var result=data.value;
433         if (result) {
434             //if (!!callback /* domid */) {
435             //    /* Directly inform the requestor */
436             //    if (manifold.asynchroneous_debug) messages.debug("directing result to callback");
437             //    callback(result);
438             //    //if (manifold.asynchroneous_debug) messages.debug("directing result to " + domid);
439             //    //jQuery('#' + domid).trigger('results', [result]);
440             //} else {
441                 /* XXX Jordan XXX I don't need publish_uuid here... What is it used for ? */
442                 /* query is the query we sent to the backend; we need to find the
443                  * corresponding analyezd_query in manifold.all_queries
444                  */
445
446                 // XXX We might need to update the corresponding update_query here 
447                 query_ext = manifold.query_store.find_query_ext(query.query_uuid);
448                 query = query_ext.query;
449
450                 // We don't prepare an update query if the result has more than 1 entry
451                 if (result.length == 1) {
452                     var res = result[0];
453
454                     console.log("Locating update query for updating params", update_query);
455                     update_query_ext = query_ext.update_query_ext;
456                     update_query = update_query_ext.query;
457
458                     // Testing whether the result has subqueries (one level deep only)
459                     // iif the query has subqueries
460                     var count = 0;
461                     var obj = query.analyzed_query.subqueries;
462                     for (method in obj) {
463                         if (obj.hasOwnProperty(method)) {
464                             var key = manifold.metadata.get_key(method);
465                             if (!key)
466                                 continue;
467                             if (key.length > 1)
468                                 continue;
469                             key = key[0];
470                             var sq_keys = [];
471                             var records = res[method];
472                             if (!records)
473                                 continue
474                             $.each(records, function (i, obj) {
475                                 sq_keys.push(obj[key]);
476                             });
477                             update_query.params[method] = sq_keys;
478                             count++;
479                         }
480                     }
481
482                     if (count > 0) {
483                         update_query_ext.disabled = false;
484                     }
485
486                 }
487
488
489                 
490                 // We have results from the main query
491                 // inspect subqueries and get the key for each
492
493                 // XXX note that we might need the name for each relation, but
494                 // this might be for SET_ADD, since we need to recursively find
495                 // the path from the main query
496
497
498                 tmp_query = manifold.find_query(query.query_uuid);
499                 manifold.publish_result_rec(tmp_query.analyzed_query, result);
500             //}
501
502         }
503     },
504
505     /************************************************************************** 
506      * Plugin API helpers
507      **************************************************************************/ 
508
509     raise_event_handler: function(type, query_uuid, event_type, value)
510     {
511         if ((type != 'query') && (type != 'record'))
512             throw 'Incorrect type for manifold.raise_event()';
513
514         var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
515
516         $.each(channels, function(i, channel) {
517             if (value === undefined)
518                 $('.plugin').trigger(channel, [event_type]);
519             else
520                 $('.plugin').trigger(channel, [event_type, value]);
521         });
522     },
523
524     raise_query_event: function(query_uuid, event_type, value)
525     {
526         manifold.raise_event_handler('query', query_uuid, event_type, value);
527     },
528
529     raise_record_event: function(query_uuid, event_type, value)
530     {
531         manifold.raise_event_handler('record', query_uuid, event_type, value);
532     },
533
534
535     raise_event: function(query_uuid, event_type, value)
536     {
537         // Query uuid has been updated with the key of a new element
538         query_ext    = manifold.query_store.find_analyzed_query_ext(query_uuid);
539         query = query_ext.query;
540
541         switch(event_type) {
542             case SET_ADD:
543                 // update is only possible is the query is not pending, etc
544                 // CHECK status !
545
546                 // XXX we can only update subqueries of the main query. Check !
547                 // assert query_ext.parent_query == query_ext.main_query
548                 update_query = query_ext.main_query_ext.update_query_ext.query;
549
550                 var path = "";
551                 var sq = query_ext;
552                 while (sq.parent_query_ext) {
553                     if (path != "")
554                         path = '.' + path;
555                     path = sq.query.object + path;
556                     sq = sq.parent_query_ext;
557                 }
558
559                 update_query.params[path].push(value);
560                 console.log('Updated query params', update_query);
561                 // NOTE: update might modify the fields in Get
562                 // NOTE : we have to modify all child queries
563                 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
564
565                 // if everything is done right, update_query should not be null. It is updated when we received results from the get query
566                 // object = the same as get
567                 // filter = key : update a single object for now
568                 // fields = the same as get
569
570                 break;
571             case SET_REMOVED:
572                 // Query uuid has been updated with the key of a removed element
573                 break;
574
575             case RUN_UPDATE:
576                 update_query = query_ext.main_query_ext.update_query_ext.query;
577                 
578                 manifold.asynchroneous_exec ( [ {'query_uuid': update_query.query_uuid, 'publish_uuid' : query_uuid} ], false);
579                 break;
580
581             case FILTER_ADDED:
582                 break;
583             case FILTER_REMOVED:
584                 break;
585             case FIELD_ADDED:
586                 main_query = query_ext.main_query_ext.query;
587                 main_update_query = query_ext.main_query_ext.update_query;
588                 query.select(value);
589
590                 // Here we need the full path through all subqueries
591                 path = ""
592                 // XXX We might need the query name in the QueryExt structure
593                 main_query.select(value);
594
595                 // XXX When is an update query associated ?
596                 // XXX main_update_query.select(value);
597
598                 break;
599
600             case FIELD_REMOVED:
601                 query = query_ext.query;
602                 main_query = query_ext.main_query_ext.query;
603                 main_update_query = query_ext.main_query_ext.update_query;
604                 query.unselect(value);
605                 main_query.unselect(value);
606
607                 // We need to inform about changes in these queries to the respective plugins
608                 // Note: query & main_query have the same UUID
609                 manifold.raise_query_event(query_uuid, event_type, value);
610                 break;
611         }
612         // We need to inform about changes in these queries to the respective plugins
613         // Note: query, main_query & update_query have the same UUID
614         manifold.raise_query_event(query_uuid, event_type, value);
615         // We are targeting the same object with get and update
616         // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
617         // NOTE: Editing a subquery == editing a local view on the destination
618
619         // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
620         // For the time being, we will collect all columns during the first query
621     },
622
623     /* Publish/subscribe channels for internal use */
624     get_channel: function(type, query_uuid) 
625     {
626         if ((type !== 'query') && (type != 'record'))
627             return null;
628         return '/' + type + '/' + query_uuid;
629     },
630
631 }; // manifold object
632 /* ------------------------------------------------------------ */
633
634 (function($) {
635
636     // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
637     // https://gist.github.com/661855
638     var o = $({});
639     $.subscribe = function( channel, selector, data, fn) {
640       /* borrowed from jQuery */
641       if ( data == null && fn == null ) {
642           // ( channel, fn )
643           fn = selector;
644           data = selector = undefined;
645       } else if ( fn == null ) {
646           if ( typeof selector === "string" ) {
647               // ( channel, selector, fn )
648               fn = data;
649               data = undefined;
650           } else {
651               // ( channel, data, fn )
652               fn = data;
653               data = selector;
654               selector = undefined;
655           }
656       }
657       /* </ugly> */
658   
659       /* We use an indirection function that will clone the object passed in
660        * parameter to the subscribe callback 
661        * 
662        * FIXME currently we only clone query objects which are the only ones
663        * supported and editable, we might have the same issue with results but
664        * the page load time will be severely affected...
665        */
666       o.on.apply(o, [channel, selector, data, function() { 
667           for(i = 1; i < arguments.length; i++) {
668               if ( arguments[i].constructor.name == 'ManifoldQuery' )
669                   arguments[i] = arguments[i].clone();
670           }
671           fn.apply(o, arguments);
672       }]);
673     };
674   
675     $.unsubscribe = function() {
676       o.off.apply(o, arguments);
677     };
678   
679     $.publish = function() {
680       o.trigger.apply(o, arguments);
681     };
682   
683 }(jQuery));
684
685 /* ------------------------------------------------------------ */
686
687 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
688 //make sure to expose csrf in our outcoming ajax/post requests
689 $.ajaxSetup({ 
690      beforeSend: function(xhr, settings) {
691          function getCookie(name) {
692              var cookieValue = null;
693              if (document.cookie && document.cookie != '') {
694                  var cookies = document.cookie.split(';');
695                  for (var i = 0; i < cookies.length; i++) {
696                      var cookie = jQuery.trim(cookies[i]);
697                      // Does this cookie string begin with the name we want?
698                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
699                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
700                      break;
701                  }
702              }
703          }
704          return cookieValue;
705          }
706          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
707              // Only send the token to relative URLs i.e. locally.
708              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
709          }
710      } 
711 });
712