f6c4f56372e45a8e0a1ef18dbbeed1db0e83b4c9
[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 /*!
23  * This namespace holds functions for globally managing query objects
24  * \Class Manifold
25  */
26 var manifold = {
27
28     /*!
29      * Associative array storing the set of queries active on the page
30      * \memberof Manifold
31      */
32     all_queries: {},
33
34     /*!
35      * Insert a query in the global hash table associating uuids to queries.
36      * If the query has no been analyzed yet, let's do it.
37      * \fn insert_query(query)
38      * \memberof Manifold
39      * \param ManifoldQuery query Query to be added
40      */
41     insert_query : function (query) { 
42         if (query.analyzed_query == null) {
43             query.analyze_subqueries();
44         }
45         manifold.all_queries[query.query_uuid]=query; 
46     },
47
48     /*!
49      * Returns the query associated to a UUID
50      * \fn find_query(query_uuid)
51      * \memberof Manifold
52      * \param string query_uuid The UUID of the query to be returned
53      */
54     find_query : function (query_uuid) { 
55         return manifold.all_queries[query_uuid];
56     },
57
58     // trigger a query asynchroneously
59     proxy_url : '/manifold/proxy/json/',
60
61     asynchroneous_debug : true,
62
63     // Executes all async. queries
64     // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
65     asynchroneous_exec : function (query_publish_dom_tuples) {
66         // start spinners
67
68         // in case the spin stuff was not loaded, let's make sure we proceed to the exit 
69         try {
70             if (manifold.asynchroneous_debug) 
71             messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
72             jQuery('.need-spin').spin(spin_presets);
73         } catch (err) { messages.debug("Cannot turn on spins " + err); }
74         
75         // We use js function closure to be able to pass the query (array) to the
76         // callback function used when data is received
77         var success_closure = function(query, publish_uuid, domid) {
78             return function(data, textStatus) {manifold.asynchroneous_success(data, query, publish_uuid, domid);}};
79         
80         // Loop through input array, and use publish_uuid to publish back results
81         jQuery.each(query_publish_dom_tuples, function(index, tuple) {
82             var query=manifold.find_query(tuple.query_uuid);
83             var query_json=JSON.stringify (query);
84             var publish_uuid=tuple.publish_uuid;
85             // by default we publish using the same uuid of course
86             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
87             if (manifold.asynchroneous_debug) {
88                 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
89                 messages.debug("... ctd... with actual query= " + query.__repr());
90             }
91             // not quite sure what happens if we send a string directly, as POST data is named..
92             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
93                 jQuery.post(manifold.proxy_url, {'json':query_json} , success_closure(query, publish_uuid, tuple.domid));
94         })
95     },
96
97     // if set domid allows the result to be directed to just one plugin
98     // most of the time publish_uuid will be query.query_uuid
99     // however in some cases we wish to publish the results under a different uuid
100     // e.g. an updater wants to publish its results as if from the original (get) query
101     asynchroneous_success : function (data, query, publish_uuid, domid) {
102         // xxx should have a nicer declaration of that enum in sync with the python code somehow
103         if (data.code == 2) { // ERROR
104             alert("Your session has expired, please log in again");
105             window.location="/logout/";
106             return;
107         }
108         if (data.code == 1) { // WARNING
109             messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
110             // publish error code and text message on a separate channel for whoever is interested
111             jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
112         }
113         // once everything is checked we can use the 'value' part of the manifoldresult
114         var value=data.value;
115         if (value) {
116             if (!!domid) {
117                 /* Directly inform the requestor */
118                 if (manifold.asynchroneous_debug) messages.debug("directing results to " + domid);
119                 jQuery('#' + domid).trigger('results', [value]);
120             } else {
121                 /* Publish an update announce */
122                 var channel="/results/" + publish_uuid + "/changed";
123                 if (manifold.asynchroneous_debug) messages.debug("publishing results on " + channel);
124                 jQuery.publish(channel, [value, query]);
125             }
126
127         }
128     },
129
130 }; // manifold object
131 /* ------------------------------------------------------------ */
132
133 // extend jQuery/$ with pubsub capabilities
134 /* https://gist.github.com/661855 */
135 (function($) {
136
137   var o = $({});
138
139   $.subscribe = function( channel, selector, data, fn) {
140     /* borrowed from jQuery */
141     if ( data == null && fn == null ) {
142         // ( channel, fn )
143         fn = selector;
144         data = selector = undefined;
145     } else if ( fn == null ) {
146         if ( typeof selector === "string" ) {
147             // ( channel, selector, fn )
148             fn = data;
149             data = undefined;
150         } else {
151             // ( channel, data, fn )
152             fn = data;
153             data = selector;
154             selector = undefined;
155         }
156     }
157     /* </ugly> */
158
159     /* We use an indirection function that will clone the object passed in
160      * parameter to the subscribe callback 
161      * 
162      * FIXME currently we only clone query objects which are the only ones
163      * supported and editable, we might have the same issue with results but
164      * the page load time will be severely affected...
165      */
166     o.on.apply(o, [channel, selector, data, function() { 
167         for(i = 1; i < arguments.length; i++) {
168             if ( arguments[i].constructor.name == 'ManifoldQuery' )
169                 arguments[i] = arguments[i].clone();
170         }
171         fn.apply(o, arguments);
172     }]);
173   };
174
175   $.unsubscribe = function() {
176     o.off.apply(o, arguments);
177   };
178
179   $.publish = function() {
180     o.trigger.apply(o, arguments);
181   };
182
183 }(jQuery));
184
185 /* ------------------------------------------------------------ */
186
187 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
188 //make sure to expose csrf in our outcoming ajax/post requests
189 $.ajaxSetup({ 
190      beforeSend: function(xhr, settings) {
191          function getCookie(name) {
192              var cookieValue = null;
193              if (document.cookie && document.cookie != '') {
194                  var cookies = document.cookie.split(';');
195                  for (var i = 0; i < cookies.length; i++) {
196                      var cookie = jQuery.trim(cookies[i]);
197                      // Does this cookie string begin with the name we want?
198                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
199                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
200                      break;
201                  }
202              }
203          }
204          return cookieValue;
205          }
206          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
207              // Only send the token to relative URLs i.e. locally.
208              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
209          }
210      } 
211 });
212